public
Last active — forked from burin/each_with_index.coffee

each_with_classes handlebars helper, adds {{item_*}} properties accessible from within the block

  • Download Gist
each_with_classes.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/**
* 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;
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.