我有一个车把页面,根据json中的标题,它会显示不同的内容。
到目前为止,这是使用 helper if_wq
构建的例如如果title = test ,则此方法有效
我想扩展此功能以显示 if title = test 和 colors.href = / test
因此该条件仅在两个条件都为真时才有效。
我的代码示例
{{#if_eq title 'test'}}
True
{{/if_eq}}
我的助手任务示例
handlebars.Handlebars.registerHelper('if_eq', function(a, b, opts) {
if (a === b) {
return opts.fn(this);
} else {
return opts.inverse(this);
}
});
我的json示例
"range-list-page": {
"ranges": [
{
"title": "test",
"colors": [
{
"color": "#fff",
"label": "White",
"bordered": true,
"href" : "/test"
},
{
"color": "#F3DCAE",
"label": "Cream",
"href" : "http://google.com"
},
{
"color": "#C5B7B0",
"label": "Cashmere",
"href" : "http://google.com"
},
{
"color": "#D0B193",
"label": "Larch",
"href" : "http://google.com"
}
]
答案 0 :(得分:1)
我定义了以下辅助方法:
(1)eq
-您已经拥有了,
Handlebars.registerHelper('eq', function(a, b) {
if(a == b) // Or === depending on your needs
return true;
else
return false;
});
(2)and
-参见下面的重要说明。
Handlebars.registerHelper('and', function () {
// Get function args and remove last one (meta object); every(Boolean) checks AND
return Array.prototype.slice.call(arguments, 0, arguments.length - 1).every(Boolean);
});
注意:如您所见,在执行arguments
之前,我必须从Array.prototype.slice.call
中删除最后一个arg,因为这里返回的最后一个arg是一个元对象。如果不修剪参数的最后结果,则every(Boolean)
会给出错误的结果。否则,它只是一个every(Boolean)
。
(3)现在,假设我们有这两个助手,下面的示例将检查AND / EQ:
{{#if (and (eq var1 'STRING1') (eq var2 'STRING2') ) }}
...
{{/if}}