Last active
August 29, 2015 14:18
-
-
Save logicmason/83b34e0a59f91cc5efc0 to your computer and use it in GitHub Desktop.
Why doesn't Handlebars have something like this built-in?
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
/** Because Handlebars sucks and won't let you iterate with @index | |
* Use this lookup helper to do things with the automatic @index var inside loops | |
* | |
* Usage example: (Get the item at @index each iteration through foo) | |
* {{#each foo}} | |
* <div>{{someProp}}</div> | |
* <div>{{lookup ../dailyStat @index}}</div> | |
* {{/each}} | |
* | |
* Block usage example: (get the item at @index in monthlyUniqueCustomers and then use its subcomponents | |
* {{#lookup monthlyUniqueCustomers @index}} | |
* <div>Count: {{count}}</div> | |
* <div>Growth: {{growth}}</div> | |
* {{/lookup}} | |
* @param {obj} object (or array) whose field is accessed in a .hbs file | |
* @param {key} key (or index) designating which field of the object to access | |
* @param {options} [options] - allows the helper to be used as a block helper | |
* @returns {string} The text to be generated by handlebars | |
*/ | |
Handlebars.registerHelper('lookup', function(obj, key, options) { | |
if (options) return options.fn(obj[key]); | |
else return obj[key]; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Even better would be if it just worked in the expected manner, i.e.