Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counter for handlebars #each

Tags:

In Handlebars, say I have a collection of names. How can I do

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

where {{position}} is 1 for the first name, 2 for the second name, etc.? Do I absolutely have to store the position as a key in the collection?

like image 360
algorithmicCoder Avatar asked Mar 01 '13 00:03

algorithmicCoder


People also ask

What are Handlebars helpers?

Custom Helpers You can create your own helpers to perform complex logics using the expression system that Handlebars provides. There are two kinds of helpers: function helpers and block helpers. The first definition is meant for a single expression, while the latter is used for block expressions.

How do you iterate objects in Handlebars?

To iterate over an object with JavaScript and Handlebars. js, we can use the #each keyword. to add the Handlebars script and the template for looping through each entry in data . We use #each this to loop through each array property.

How do I register helper Handlebars?

js or <script> tag or anywhere else, you need to have access to Handlebars object, since you are invoking registerHelper method on that object (which injects a helper into that object). After Handlebars has been modified, every module referencing that object will have access to the new helper.


1 Answers

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/

like image 151
Smix Avatar answered Sep 22 '22 18:09

Smix