比较空格键 {{#if}} 块中的模板助手值
Compare template helper values in Spacebars {{#if}} block
我需要比较位于嵌套模板中的两个模板助手值。我想知道是否有一种简单的方法可以在 {{#if}} 语句中比较两个模板助手(一个来自父模板),如下所示:
{{#each bids}}
{{#if bid.price===../job.price}}
<span>some text</span>
{{else}}
<span>some other text</span>
{{/if}}
{{/each}}
如果你不能这样做,我想另一个选择是在每个块内的新模板中使用 Template.parentData?我不反对这个,如果可能的话,我上面概述的方法会更快更简单。谢谢
我相信你是对的,空格键不支持 #if
条件下的逻辑语句。但是您可以轻松定义一个新的块助手:
HandlebarsRegister.registerHelper('ifx', function(conditional, options) {
var truthValue = false;
try {
truthValue = eval(conditional);
} catch (e) {
console.log("Exception in #ifx evaluation of condition: ",
conditional, e);
}
if (truthValue) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
然后使用
{{#each bids}}
{{#ifx "bid.price===../job.price"}}
<span>some text</span>
{{else}}
<span>some other text</span>
{{/ifx}}
{{/each}}
唯一的缺点是您需要将条件写成字符串,eval
并不十分优雅。但是,嘿,它有效。
类似这样的东西可能对你有用:
Template.registerHelper('_', function(){
return _
})
{{#each bids}}
{{#if _.isEqual bid.price ../job.price}}
<span>some text</span>
{{else}}
<span>some other text</span>
{{/if}}
{{/each}}
作为奖励,您不仅可以获得 _.isEqual
,还可以获得所有 _.* 函数。
我需要比较位于嵌套模板中的两个模板助手值。我想知道是否有一种简单的方法可以在 {{#if}} 语句中比较两个模板助手(一个来自父模板),如下所示:
{{#each bids}}
{{#if bid.price===../job.price}}
<span>some text</span>
{{else}}
<span>some other text</span>
{{/if}}
{{/each}}
如果你不能这样做,我想另一个选择是在每个块内的新模板中使用 Template.parentData?我不反对这个,如果可能的话,我上面概述的方法会更快更简单。谢谢
我相信你是对的,空格键不支持 #if
条件下的逻辑语句。但是您可以轻松定义一个新的块助手:
HandlebarsRegister.registerHelper('ifx', function(conditional, options) {
var truthValue = false;
try {
truthValue = eval(conditional);
} catch (e) {
console.log("Exception in #ifx evaluation of condition: ",
conditional, e);
}
if (truthValue) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
然后使用
{{#each bids}}
{{#ifx "bid.price===../job.price"}}
<span>some text</span>
{{else}}
<span>some other text</span>
{{/ifx}}
{{/each}}
唯一的缺点是您需要将条件写成字符串,eval
并不十分优雅。但是,嘿,它有效。
类似这样的东西可能对你有用:
Template.registerHelper('_', function(){
return _
})
{{#each bids}}
{{#if _.isEqual bid.price ../job.price}}
<span>some text</span>
{{else}}
<span>some other text</span>
{{/if}}
{{/each}}
作为奖励,您不仅可以获得 _.isEqual
,还可以获得所有 _.* 函数。