Skip to content

Instantly share code, notes, and snippets.

@willywongi
Forked from burin/each_with_index.coffee
Created September 18, 2012 11:47
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 willywongi/3742739 to your computer and use it in GitHub Desktop.
Save willywongi/3742739 to your computer and use it in GitHub Desktop.
each_with_index handlebars helper, adds an {{index}} prop accessible from within the block
Handlebars.registerHelper 'each_with_index', (array, fn) ->
buffer = ''
for i in array
item = i
item.index = _i
buffer += fn(item)
buffer
// {{#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 buffer = [];
for (var i = 0, j = array.length; 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;
// show the inside of the block
buffer.push(fn(item));
}
// return the finished buffer
return buffer.join('');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment