Counter for handlebars #each

后端 未结 8 967
小鲜肉
小鲜肉 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:58

    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!

提交回复
热议问题