在 underscore.js 模板中使变量可选
我有这样的代码:
_.templateSettings = {interpolate : /\{\{(.+?)\}\}/g};
var _d = _.template($('#_d').html());
$.get('/foo', function(data) {
$('#output').html(_d(data));
});
在 HTML 中:
<div id="_d">
{{name}} {{phone}}
</div>
<div id="output"></div>
/foo
返回类似于 {"name":"joe","phone":"12345"}
的内容,但有时它不会没有 phone
因此只会返回 {"name":"joe"}
,这将阻碍模板评估,因此在 output
中不会打印任何内容。如何使变量可选?
编辑: /foo
超出我的控制范围
I have this code:
_.templateSettings = {interpolate : /\{\{(.+?)\}\}/g};
var _d = _.template($('#_d').html());
$.get('/foo', function(data) {
$('#output').html(_d(data));
});
and in HTML:
<div id="_d">
{{name}} {{phone}}
</div>
<div id="output"></div>
/foo
returns something like {"name":"joe","phone":"12345"}
, but sometimes it doesn't have phone
thus simply returns {"name":"joe"}
, which will choke template evaluation thus nothing gets printed in output
. How do I make a variable optional?
EDIT: /foo
is beyond my control
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
||
运算符对于此类事情非常有用:但是由于您已经在使用 Underscore,因此您可以使用
_.defaults
函数。这种方法对于为多个字段提供默认值特别有用:The
||
operator is useful for this sort of thing:But since you're already using Underscore, you can use the
_.defaults
function. This approach is particularly useful for providing defaults for multiple fields:我喜欢@namuol 解决方案,我们可以做的另一件事是在模型扩展中设置默认哈希
只是另一个选项。
I liked @namuol solution, another thing that we could do is set the defaults hash at the model extends
Just another option.
您可以有一个 html
使用如下模板来避免
phone
的未定义变量问题You can have an html
Use the template as below to avoid undefined variable issue for
phone
一个实用的解决方案是在对象中包含
phone
,但值为空:A practical solution would be to include
phone
in the object, but with an empty value:上面有一些很好的答案,但是您可以使用
_.partial
来获得应用具有默认值的模板的单个函数:There are some good answers above, but you can use
_.partial
to get a single function that applies a template with defaults:然后是显而易见的:将其放在模板的顶部:
工作片段:
(也如 jsfiddle)
And then there is the obvious: Put this in the top of your template:
Working snippet:
(also as jsfiddle)