Iterating over basic “for” loop using Handlebars.js

前端 未结 5 1132
轻奢々
轻奢々 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: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;
    });
    

提交回复
热议问题