如果我有类似的话:
{
people: [
"Yehuda Katz",
"Alan Johnson",
"Charles Jolley"
]
}
如何获取车把中每个值的位置?
{{#each people}}
{{this}}
<!--{{this.position}} -->
{{/each}}
我希望答案是
Yehuda Katz
0
Alan Johnson
1
Charles Jolley
2
答案 0 :(得分:1)
您可以定义自己的块表达式,例如'each_with_index',以实现此目的。您可以在此处的Handlebars文档中找到如何创建此自定义表达式:http://handlebarsjs.com/#block-expressions
这是一种快速而肮脏的方法:
var people = [ 'Yehuda Katz', 'Alan Johnson', 'Charles Jolley' ];
var source = '{{#each_with_index people}}' +
'{{ this.index }}: {{ this.item }}\n' +
'{{/each_with_index}}';
Handlebars.registerHelper('each_with_index', function(items, options) {
var output = '';
var item_count = items.length;
var item;
for (var index = 0; index < item_count; index ++) {
item = items[index];
output = output + options.fn({ item: item, index: index });
}
return output;
});
var $output = $('#output');
var template = Handlebars.compile(source);
var result = template({ people: people });
$output.html(result);
要查看它是否有效:http://jsfiddle.net/EECFR/1/
答案 1 :(得分:0)
使用@index
:
{{#each people}}
{{this}}
{{@index}}
{{/each}}
JSFiddle demo(由Carl改编)
来自http://handlebarsjs.com/#iteration:
循环遍历每个项目时,您可以选择通过
引用当前循环索引{{@index}}
{{#each array}}
{{@index}}: {{this}}
{{/each}}