Counter for handlebars #each

后端 未结 8 1082
小鲜肉
小鲜肉 2021-02-04 02:29

In Handlebars, say i have a collection of names how can i do

{{#each names}}
{{position}}
{{name}}
{{/each}}

where {{position}} is

8条回答
  •  無奈伤痛
    2021-02-04 02:49

    Here is my preferred solution. Register a helper that extends the context to include your position property automatically. Then just use your new block helper (ex. #iter) instead of #each.

    Handlebars.registerHelper('iter', function (context, options) {
        var ret = "";
    
        for (var i = 0, j = context.length; i < j; i++) {
            ret += options.fn($.extend(context[i], {position: i + 1}));
        }
    
        return ret;
    });
    

    Usage:

    {{#iter names}}
        {{position}}
        {{name}}
    {{/iter}}
    

    adapted from http://rockycode.com/blog/handlebars-loop-index/

提交回复
热议问题