我遇到了#each和#if helper的问题。首先我在http://handlebarsjs.com/block_helpers.html,but寻找解决方案我没找到任何东西。 例如: 有对象:
{ peoples: [{ name:"A", age:16, sex:"boy" },{ name:"B", age:14, sex:"boy" },{ name:"C", age:18, sex:"boy" }] };
在html中(伪代码,我想要,但我不知道如何完成它们。)
{{#each peoples}} {{#if age equal 16}} {{name}} can drive {{/if}} {{#if age smaller than 16}} {{name}} can't drive {{/if}} {{#if age bigger than 16}} {{name}} can do anything {{/if}} {{/each}}
或
{{#each peoples}} {{#if equal(name,"A")}} {{name}} can drive {{/if}} {{#if equal(name,"B")} {{name}} can't drive {{/if}} {{#if equal(name,"c")}} {{name}} can do anything {{/if}} {{/each}}
感谢您的投入。
答案 0 :(得分:1)
您需要使用自定义表达式帮助程序。
Handlebars.registerHelper('getDriveStatus', function(age, name) {
if (age == 16) {
return name + " can drive"
}
if (age < 16) {
return name + " can't drive";
}
if (age > 16) {
return name + " can't do anything";
}
});
然后,
{{#each peoples}}
{{getDriveStatus age name}}
{{/each}}
与角色条件相同。
答案 1 :(得分:1)
您可以在Template.YourTemplate.helpers({})部分中创建辅助函数:
Template.YourTemplate.helpers({
'canDrive' : function(name, age){
if (age == 16) { return name + " can drive" }
if (age < 16) { return name + " can't drive"; }
if (age > 16) { return name + " can't do anything"; }
},
})
在您的模板中,您可以像这样使用它:
{{#each peoples}}
{{canDrive name age}}
{{/each}}
答案 2 :(得分:1)
谢谢@Prashant和@Oscar,我得到了问题的解决方案。 他们的回复很有帮助。如果你有同样的问题,试着去做。 没有Handlebars.registerHelper的解决方案:
在html中:
{{#each peoples}} {{#if equal name "A"}}{{age}}{{sex}}{{/if}} {{/each}}
在客户端:
Template.test.equal = function (a,b) { return a===b; };