Skip to content

Instantly share code, notes, and snippets.

@icodeforlove
Forked from burin/each_with_index.coffee
Created December 4, 2011 05:43
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save icodeforlove/1429324 to your computer and use it in GitHub Desktop.
each_with_classes handlebars helper, adds {{item_*}} properties accessible from within the block
/**
* adds an a bunch of item prefixed logic to the object
*
* {{#each_with_classes records prefix="record"}}
* <li class="record_{{item_index}}{{item_position}} {{item_alt}}">{{item_index}}</li>
* {{/each_with_classes}}
*
* results in the following html
*
* <li class="record_0 record_first">0</li>
* <li class="record_1 record_alt">1</li>
* <li class="record_2">2</li>
* <li class="record_3 record_last record_alt">3</li>
*/
Handlebars.registerHelper("each_with_classes", function(array, fn) {
var buffer = "";
for (var i = 0, j = array.length; i < j; i++) {
var item = array[i];
// position related information
item.item_position = '';
if (i == 0) item.item_position = ' ' + fn.hash.prefix + '-first';
if (i == (array.length - 1)) item.item_position += ' ' + fn.hash.prefix + '-last';
// add alt if needed
item.item_alt = i % 2 ? fn.hash.prefix + '-alt' : '';
// stick an index property onto the item, starting with 1, may make configurable later
item.item_index = i;
// 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