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?
you can get value just from index inside the list.
only you have to use {{@index}}
example:
Usage:
You can do this with the built-in Handlebars @index notation:
@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/
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.
Usage:
adapted from http://rockycode.com/blog/handlebars-loop-index/
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 callregisterHelper
. Here is an example of how you can register a helper calledposition
that should work with your template example.JavaScript:
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!