Last active
March 24, 2022 16:32
-
-
Save amitkumar/b1969e86e1379db83511 to your computer and use it in GitHub Desktop.
Useful Handlebars Helpers. Get specific array item, if equals filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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