使用Handlebars.js迭代基本的"for"循环

use*_*100 75 handlebars.js

我是Handlebars.js的新手,刚刚开始使用它.大多数示例都基于迭代对象.我想知道如何在基本的循环中使用把手.

例.

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

怎么能实现这一目标?

mu *_*ort 169

Handlebars中没有任何内容,但您可以轻松添加自己的帮助程序.

如果你只想做一些事情n,那么:

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

{{#times 10}}
    <span>{{this}}</span>
{{/times}}
Run Code Online (Sandbox Code Playgroud)

如果你想要一个完整的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;
});
Run Code Online (Sandbox Code Playgroud)

{{#for 0 10 2}}
    <span>{{this}}</span>
{{/for}}
Run Code Online (Sandbox Code Playgroud)

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


Mik*_*lor 17

如果您想使用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;
});
Run Code Online (Sandbox Code Playgroud)

{{#times 10}}
    <span> {{@first}} {{@index}} {{@last}}</span>
{{/times}}
Run Code Online (Sandbox Code Playgroud)

  • 这个助手在嵌套使用助手时似乎不允许使用 @../index 或 @../last 。这是对的还是我做错了什么? (2认同)

小智 8

如果你喜欢CoffeeScript

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

{{#times 10}}
  <span>{{this}}</span>
{{/times}}
Run Code Online (Sandbox Code Playgroud)


Seb*_*čić 8

晚了几年,但现在eachHandlebars 中提供了它,它允许您轻松地迭代一系列项目。

https://handlebarsjs.com/guide/builtin-helpers.html#each


dmi*_*i3y 6

这个片段将处理else块,以防n作为动态值,并提供@index可选的上下文变量,它将保持执行的外部上下文.

/*
* 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;
});
Run Code Online (Sandbox Code Playgroud)