2012-08-12 181 views
62

我是Handlebars.js的新手,刚开始使用它。大多数例子都是基于迭代一个对象的。我想知道如何在基本for循环中使用handlebars。使用Handlebars.js迭代基本“for”循环

例子。

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

这是如何实现的?

回答

141

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/

+1

+1的帮手。作为一个方面说明,在需要引用初始数据的场景中,嵌套助手不起作用。即数据:{行数:12,列数:3}。 – backdesk 2014-03-19 15:55:56

+0

@ mu-is-too-short对这里有帮助吗? http://stackoverflow.com/questions/28865379/handlebar-helper-syntax-in-ember-cli – sheriffderek 2015-03-04 21:30:14

+0

@sheriffderek对不起,我不知道东西的Ember或Ember-CLI方面。 – 2015-03-04 22:22:51

7

如果你喜欢的CoffeeScript

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

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

这个片段会照顾别人块的情况下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; 
}); 
+0

我更喜欢这种方法,因为您手边有@index变量。您也可以根据具体需要轻松添加其他变量。 – ChrisRich 2016-01-29 10:15:27

10

顶部的回答是不错的,如果你想用最后/第一/指数虽然你可以使用下面的

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}} 
+0

这个帮助程序在嵌套使用Helper时似乎不允许使用@ ../index或@ ../last。这是正确的,或者我做错了什么? – madtyn 2017-06-13 10:43:55