我想创建一个全局计数器,每次使用它时都会被下一个值替换,例如{{Counter}}如果我在模板中使用如下所示
>这是{{Counter}}行
>这是{{Counter}}行
>这是{{Counter}}行
>这是{{Counter}}行
然后将呈现为
>这是第1行
>这是第2行
>这是第3行
>这是第4行
这是否可以通过handlebarJS
最佳答案 您可以使用HandlebarsHelper来实现这一目标.
var temp = 1;
Handlebars.registerHelper('Counter', function() {
return temp++;
});
你的Handlebars模板是,
This is line {{Counter}}
This is line {{Counter}}
This is line {{Counter}}
This is line {{Counter}}
哪个输出
This is line 1
This is line 2
This is line 3
This is line 4
测试使用 – http://tryhandlebarsjs.com/
希望这可以帮助.