Skip to content

Instantly share code, notes, and snippets.

@leandono
Forked from gabrielstuff/each_with_index.js
Created June 7, 2012 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leandono/2889952 to your computer and use it in GitHub Desktop.
Save leandono/2889952 to your computer and use it in GitHub Desktop.
[handlebars] each_with_index handlebars helper, adds an {{index}} prop accessible from within the block
// {{#each_with_index records}}
// <li class="legend_item{{index}}"><span></span>{{Name}}</li>
// {{/each_with_index}}
Handlebars.registerHelper("each_with_index", function(array, fn) {
var total = array.length;
var buffer = "";
//Better performance: http://jsperf.com/for-vs-foreach/2
for (var i = 0, j = total; i < j; i++) {
var item = array[i];
// stick an index property onto the item, starting with 1, may make configurable later
item.index = i+1;
item.total = total;
// show the inside of the block
buffer += fn(item);
}
// return the finished buffer
return buffer;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment