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


77

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

例。

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

如何做到这一点?

Answers:


177

把手里没有任何东西,但是您可以足够轻松地添加自己的助手。

如果您只是想做一些事情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/


1
+1帮手。附带说明一下,在需要参考原始数据的情况下,嵌套for helper无效。即数据:{行:12,列:3}。
2014年

@ mu-is-too-short在这里有什么帮助吗?stackoverflow.com/questions/28865379/…–
sheriffderek

@sheriffderek对不起,我不了解Ember或Ember-CLI方面。
亩太短

1
{{../this}}嵌套{{#times}}块内打印时,我注意到有时它会[Object object]代替实际的数字(每个嵌套循环一次)。
花花公子

@dude你有一个可运行的例子吗?我好几年没碰过把手了。
亩太短了,

21

如果您想使用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}}

2
当涉及到该助手的嵌套使用时,该助手似乎不允许使用@ .. / index或@ .. / last。这是对的,还是我做错了?
madtyn

8

如果您喜欢CoffeeScript

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

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

8

该代码片段将处理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;
});

1
我更喜欢这种方法,因为您手头有@index变量。您还可以根据特定需要轻松添加其他变量。
克里斯里奇
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.