Skip to content

Instantly share code, notes, and snippets.

@emamut
Last active August 18, 2016 19:21
Show Gist options
  • Save emamut/e537de9cc71457ac0b39 to your computer and use it in GitHub Desktop.
Save emamut/e537de9cc71457ac0b39 to your computer and use it in GitHub Desktop.
Handlebars useful helpers
Handlebars.registerHelper('grouped_each', function(every, context, options) {
var out = "", subcontext = [], i;
if (context && context.length > 0) {
for (i = 0; i < context.length; i++) {
if (i > 0 && i % every === 0) {
out += options.fn(subcontext);
subcontext = [];
}
subcontext.push(context[i]);
}
out += options.fn(subcontext);
}
return out;
});
Handlebars.registerHelper("debug", function(optionalValue) {
console.log("\nCurrent Context");
console.log("====================");
console.log(this);
if (arguments.length > 1) {
console.log("Value");
console.log("====================");
console.log(optionalValue);
}
});
Handlebars.registerHelper('if_eq', function(a, b, opts) {
if(a == b) // Or === depending on your needs
return opts.fn(this);
else
return opts.inverse(this);
});
Handlebars.registerHelper('return_object_item', function(obj, field, key) {
var result = $.grep(obj, function(e){ return e.pais == field; });
return result[0][key];
});
Handlebars.registerHelper('if_odd', function(conditional, options) {
if((conditional % 2) != 0) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
Handlebars.registerHelper("inc", function(value, options)
{
return parseInt(value) + 1;
});
Handlebars.registerHelper('toLowerCase', function(str) {
return str.toLowerCase();
});
Handlebars.registerHelper('toSelector', function(str) {
return str.split(' ').join('-');
});
// format an ISO date using Moment.js
// http://momentjs.com/
// moment syntax example: moment(Date("2011-07-18T15:50:52")).format("MMMM YYYY")
// usage: {{dateFormat creation_date format="MMMM YYYY"}}
Handlebars.registerHelper('dateFormat', function(context, block) {
if (window.moment) {
var f = block.hash.format || "MMM Do, YYYY";
return moment(context).format(f);
}else{
return context; // moment plugin not available. return data as is.
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment