public
Created

  • Download Gist
eachHelper.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
// 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;
});
ifHelper.js
JavaScript
1 2 3 4 5 6 7
Handlebars.registerHelper('if', function(context, options) {
if(!context || Handlebars.Utils.isEmpty(context)) {
return options.inverse(this);
} else {
return options.fn(this);
}
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.