Iterating over basic “for” loop using Handlebars.js

前端 未结 5 1014
轻奢々
轻奢々 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}}
        <span> {{@first}} {{@index}} {{@last}}</span>
    {{/times}}
    
    0 讨论(0)
  • 2020-11-30 21:35

    If you like CoffeeScript

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

    and

    {{#times 10}}
      <span>{{this}}</span>
    {{/times}}
    
    0 讨论(0)
  • 2020-11-30 21:47

    Couple of years late, but there's now each available in Handlebars which allows you to iterate pretty easily over an array of items.

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

    0 讨论(0)
  • 2020-11-30 21:51

    There's nothing in Handlebars for this but you can add your own helpers easily enough.

    If you just wanted to do something n times then:

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

    and

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

    If you wanted a whole for(;;) loop, then something like this:

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

    and

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

    Demo: http://jsfiddle.net/ambiguous/WNbrL/

    0 讨论(0)
  • 2020-11-30 21:55

    This snippet will take care of else block in case n comes as dynamic value, and provide @index optional context variable, it will keep the outer context of the execution as well.

    /*
    * 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 讨论(0)
提交回复
热议问题