Skip to content

Instantly share code, notes, and snippets.

@logicmason
Last active August 29, 2015 14:18
Show Gist options
  • Save logicmason/83b34e0a59f91cc5efc0 to your computer and use it in GitHub Desktop.
Save logicmason/83b34e0a59f91cc5efc0 to your computer and use it in GitHub Desktop.
Why doesn't Handlebars have something like this built-in?
/** 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];
});
@logicmason
Copy link
Author

Even better would be if it just worked in the expected manner, i.e.

{{#each foo}}
  <div>{{someProp}}</div>
  <div>{{../dailyStat.@index}}</div>
{{/each}}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment