Iterating over basic “for” loop using Handlebars.js

前端 未结 5 1103
轻奢々
轻奢々 2020-11-30 21:04

I’m new to Handlebars.js and just started using it. Most of the examples are based on iterating over an object. I wanted to know how to use handlebars in basic for loop.

5条回答
  •  醉梦人生
    2020-11-30 21:33

    Top answer here is good, if you want to use last / first / index though you could use the following

    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;
    });
    

    and

    {{#times 10}}
         {{@first}} {{@index}} {{@last}}
    {{/times}}
    

提交回复
热议问题