Skip to content

Instantly share code, notes, and snippets.

@wycats
Created July 27, 2011 02:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wycats/1108513 to your computer and use it in GitHub Desktop.
Save wycats/1108513 to your computer and use it in GitHub Desktop.
// original each helper
Handlebars.registerHelper('each', function(context, options) {
var fn = options.fn, inverse = options.inverse;
var ret = "";
if(context && context.length > 0) {
for(var i=0, j=context.length; i<j; i++) {
ret = ret + fn(context[i]);
}
} else {
ret = inverse(this);
}
return ret;
});
// each with index... relies on Object.create or polyfill
Handlebars.registerHelper('each', function(context, options) {
var fn = options.fn, inverse = options.inverse, ctx;
var ret = "";
if(context && context.length > 0) {
for(var i=0, j=context.length; i<j; i++) {
ctx = Object.create(context[i]);
ctx.index = i;
ret = ret + fn(ctx);
}
} else {
ret = inverse(this);
}
return ret;
});
// each with named index
//
// used as:
// {{#each people index="id"}}{{name}} #{{id}}{{/each}}
Handlebars.registerHelper('each', function(context, options) {
var fn = options.fn, inverse = options.inverse, ctx;
var ret = "", indexName = options.hash.index;
if(context && context.length > 0) {
for(var i=0, j=context.length; i<j; i++) {
ctx = context[i];
if (indexName) {
ctx = Object.create(ctx);
ctx[indexName] = i;
}
ret = ret + fn(ctx);
}
} else {
ret = inverse(this);
}
return ret;
});
Handlebars.registerHelper('if', function(context, options) {
if(!context || Handlebars.Utils.isEmpty(context)) {
return options.inverse(this);
} else {
return options.fn(this);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment