Counter for handlebars #each

我是研究僧i 提交于 2019-12-02 22:46:52

You can do this with the built-in Handlebars @index notation:

{{#each array}}
  {{@index}}: {{this}}
{{/each}}

@index will give the (zero-based) index of each item in the given array.

Please note for people using Handlebars with the Razor view engine you must use the notation @@index to avoid compilation errors.

For more built-in helpers see http://handlebarsjs.com/

Handlebars.registerHelper("counter", function (index){
    return index + 1;
});

Usage:

{{#each names}}
    {{counter @index}}
    {{name}}
{{/each}}

While you can't do this with any native Handlebars helper, you can create your own. You can call Handlebars.registerHelper(), passing it a string with the name you want to match (position), and a function that would return the current position count. You can keep track of the position number in the closure where you call registerHelper. Here is an example of how you can register a helper called position that should work with your template example.

JavaScript:

// Using a self-invoking function just to illustrate the closure
(function() {
    // Start at 1, name this unique to anything in this closure
    var positionCounter = 1;

    Handlebars.registerHelper('position', function() {
        return positionCounter++;
    });

    // Compile/render your template here
    // It will use the helper whenever it seems position
})();

Here is a jsFiddle to demonstrate: http://jsfiddle.net/willslab/T5uKW/1/

While helpers are documented on handlebarsjs.com, this took some effort for me to figure out how to use them. Thanks for the challenge, and I hope that helps!

only you have to use {{@index}}

example:

{{#.}}
<li class="order{{@index}}"> counter: {{@index}}</li>
{{/.}}

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/

you can get value just from index inside the list.

{{#each list}}
    @index
{{/each}}

This works for me

<td>{{@index}}</td>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!