Jea*_*ent 1 javascript templating mustache
使用handlebars.js,我想显示两个html块,具体取决于生成的json。
假设我要感谢用户在我的商店订购商品。我这样写我的handlerbars.js模板:
<p>{{name}}</p>
{{#if costIsZero}}
Can't find any order
{{else}}
You bought {{cost}} items in our shop, thanks.
{{/if}}
Run Code Online (Sandbox Code Playgroud)
我正在为costIsZero编写一个简单的助手,如下所示:
Handlebars.registerHelper('costIsZero', function(){
return this.cost == 0
});
Run Code Online (Sandbox Code Playgroud)
当我将其与以下json数据混合时:
var data = {
"name":"foo",
"cost": 9
};
Run Code Online (Sandbox Code Playgroud)
无论“成本”的值是什么,{{#if costIsZero}}似乎总是正确的。如果我注释掉助手本身,因此对costIsZero没有任何帮助,它将始终返回false。
上面的所有代码都可以在http://jsfiddle.net/gsSyt/中作为JSFiddle获得。
我做错了什么?
也许我正在劫持handlebars.js的工作方式,但是在那种情况下,我应该如何使用handlebars.js实现我的功能?
计算诸如的表达式时,不会调用辅助函数costIsZero。
您可以创建一个自定义帮助程序来替代if:
Handlebars.registerHelper('ifCostIsZero', function(block) {
if (this.cost == 0) {
return block(this);
} else {
return block.inverse(this);
}
});
Run Code Online (Sandbox Code Playgroud)
您将这样使用:
{{#ifCostIsZero}}
Can't find any order
{{else}}
You bought {{cost}} items in our shop, thanks.
{{/ifCostIsZero}}
Run Code Online (Sandbox Code Playgroud)
另外,由于您的测试与零相对,您可以使用stock if(或unless):
{{#if cost}}
You bought {{cost}} items in our shop, thanks.
{{else}}
Can't find any order
{{/if}}
Run Code Online (Sandbox Code Playgroud)
您可以在http://jsfiddle.net/gsSyt/41/上同时使用这两个选项
| 归档时间: |
|
| 查看次数: |
4303 次 |
| 最近记录: |