使用Handlebars.js遍历基本的“for”循环

我是Handlebars.js的新手,刚开始使用它。 大部分的例子是基于迭代一个对象的。 我想知道如何使用基本的循环句柄。

例。

for(i=0 ; i<100 ; i++) { create li's with i as the value } 

这怎么能实现?

Handlebars里没有这个,但是你可以很容易地添加你自己的助手。

如果你只是想做n次,那么:

 Handlebars.registerHelper('times', function(n, block) { var accum = ''; for(var i = 0; i < n; ++i) accum += block.fn(i); return accum; }); 

 {{#times 10}} <span>{{this}}</span> {{/times}} 

如果你想整个for(;;)循环,那么像这样:

 Handlebars.registerHelper('for', function(from, to, incr, block) { var accum = ''; for(var i = from; i < to; i += incr) accum += block.fn(i); return accum; }); 

 {{#for 0 10 2}} <span>{{this}}</span> {{/for}} 

演示: http : //jsfiddle.net/ambiguous/WNbrL/

如果你想使用last / first / index,虽然你可以使用下面的代码,但是这里最好的答案是好的

 Handlebars.registerHelper('times', function(n, block) { var accum = ''; for(var i = 0; i < n; ++i) { block.data.index = i; block.data.first = i === 0; block.data.last = i === (n - 1); accum += block.fn(this); } return accum; }); 

 {{#times 10}} <span> {{@first}} {{@index}} {{@last}}</span> {{/times}} 

如果你喜欢CoffeeScript

 Handlebars.registerHelper "times", (n, block) -> (block.fn(i) for i in [0...n]).join("") 

 {{#times 10}} <span>{{this}}</span> {{/times}} 

这个代码片段将在其他情况下阻塞,如果n为dynamic值,并提供@index可选的上下文variables,它将保持执行的外部上下文。

 /* * Repeat given markup with given times * provides @index for the repeated iteraction */ Handlebars.registerHelper("repeat", function (times, opts) { var out = ""; var i; var data = {}; if ( times ) { for ( i = 0; i < times; i += 1 ) { data.index = i; out += opts.fn(this, { data: data }); } } else { out = opts.inverse(this); } return out; });