您可以定义自己的块表达式,例如“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/