Skip to content

Instantly share code, notes, and snippets.

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 pridemusvaire/ba964b2a3e18c80115aef5430460206e to your computer and use it in GitHub Desktop.
Save pridemusvaire/ba964b2a3e18c80115aef5430460206e to your computer and use it in GitHub Desktop.
Useful Handlebars Helpers. Get specific array item, if equals filter
<script id="if_equals_example" type="text/x-handlebars-template">
{{#if_equals objectType 'message'}}
<div class="message">
Message
</div>
{{else}}
{{/if_equals}}
</script>
<script id="array_item_example" type="text/x-handlebars-template">
<span class="first-friend-name">{{#array_item friends 0}}{{firstName}} {{lastName}}{{/array_item}}</span>
</script>
<script id="each_upto_example" type="text/x-handlebars-template">
<ul>
{{#each_upto friends 3}}
<li class="item item-{{@itemIndex}}"></li>
{{/each_upto}}
</ul>
</script>
Handlebars.registerHelper('if_equals', function(conditional, value, options) {
if (conditional === value){
return options.fn(this);
} else {
return options.inverse(this);
}
});
Handlebars.registerHelper('array_item', function(array, index, options) {
return options.fn(array[index]);
});
/**
* @param ary {Array}
* @param max {Number} The max number of items to display from the array
* @param [options.skip] {Number=0} Optional. Number of items to skip in the array
*/
Handlebars.registerHelper('each_upto', function(ary, max, options) {
if(!ary || ary.length == 0)
return options.inverse(this);
var result = [],
skip = (options.hash ? (options.hash.skip ? options.hash.skip : 0) : 0),
i = skip;
max += skip;
for(; i < max && i < ary.length; ++i) {
result.push(options.fn(ary[i], { data : { itemIndex : i } } ));
}
return result.join('');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment