Skip to content

Instantly share code, notes, and snippets.

@asrashley
Forked from strathmeyer/handlebars.object_helpers.js
Last active December 20, 2015 08:59
Show Gist options
  • Select an option

  • Save asrashley/6104312 to your computer and use it in GitHub Desktop.

Select an option

Save asrashley/6104312 to your computer and use it in GitHub Desktop.
// HELPER: #key_value
//
// Usage: {{#key_value obj}} Key: {{key}} // Value: {{value}} {{/key_value}}
//
// Iterate over an object, setting 'key' and 'value' for each property in
// the object.
Handlebars.registerHelper("key_value", function(obj, block) {
var buffer = [],
key;
if(typeof(obj)=='string'){
obj = this.get(obj);
}
for (key in obj) {
if (obj.hasOwnProperty(key)) {
buffer.push(block.fn({key: key, value: obj[key]}));
}
}
return buffer.join('');
});
// HELPER: #each_with_key
//
// Usage: {{#each_with_key container key="myKey"}}...{{/each_with_key}}
//
// Iterate over an object containing other objects. Each
// inner object will be used in turn, with an added key ("myKey")
// set to the value of the inner object's key in the container.
Handlebars.registerHelper("each_with_key", function(obj, fn) {
var context,
buffer = "",
key,
keyName = fn.hash.key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
context = obj[key];
if (keyName) {
context[keyName] = key;
}
buffer += fn(context);
}
}
return buffer;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment