这是JSON数组:
{
"profile": [
{
"ID": 343,
"gender": "female",
"from": "Olivia"
},
{
"ID": 4543,
"gender": "female",
"from": "Meagen"
},
{
"ID": 787,
"gender": "male",
"from": "Aaron"
}
]
}
这样可以输出数组中的所有对象......
{{#profile}}
{{from}} {{gender}}
{{/profile}}
输出看起来像......
Olivia female
Meagen female
Aaron male
但我的目标是只圈出那些性别等于女性的人。有点像...
{{#profile gender="female"}}
{{from}} {{gender}}
{{/profile}}
...并使输出看起来像......
Olivia female
Meagen female
我几天都在努力寻找答案。我错过了什么,还是偏离轨道?
答案 0 :(得分:5)
我看到两个选项:
第一个很直接。
第二个取决于你想怎么做。您可以添加“if equal”帮助程序:
Handlebars.registerHelper('if_eq', function(a, b, block) {
return a == b
? block(this)
: block.inverse(this);
});
并在您的模板中执行此操作:
{{#profile}}
{{#if_eq gender "female"}}
{{from}} {{gender}}
{{/if_eq}}
{{/profile}}
演示:http://jsfiddle.net/ambiguous/NnH83/
或者你可以用各种方式编写自己的迭代器:
Handlebars.registerHelper('each_female', function(list, opts) {
var i, result = '';
for(i = 0; i < list.length; ++i)
if(list[i].gender == 'female')
result = result + opts.fn(list[i]);
return result;
});
{{#each_female profile}}
{{from}} {{gender}}
{{/each_female}}
或者更一般:
Handlebars.registerHelper('each_when', function(list, k, v, opts) {
console.log(arguments);
var i, result = '';
for(i = 0; i < list.length; ++i)
if(list[i][k] == v)
result = result + opts.fn(list[i]);
return result;
});
{{#each_when profile "gender" "female"}}
{{from}} {{gender}}
{{/each_when}}
演示:http://jsfiddle.net/ambiguous/E4jTs/,http://jsfiddle.net/ambiguous/AkZxN/
如果您想要更接近建议语法的内容,请参阅Hash Arguments上的fine manual。