Skip to content

Instantly share code, notes, and snippets.

@tcelestino
Last active December 31, 2015 23:48
Show Gist options
  • Select an option

  • Save tcelestino/8062003 to your computer and use it in GitHub Desktop.

Select an option

Save tcelestino/8062003 to your computer and use it in GitHub Desktop.
Handlebars Helpers
// console
Handlebars.registerHelper("debug", function(optionalValue) {
console.log("Current Context");
console.log("====================");
console.log(this);
if (optionalValue) {
console.log("Value");
console.log("====================");
console.log(optionalValue);
}
});
// remove accents
Handlebars.registerHelper("string_accents", function(values) {
var map = { 'Í':'I', 'í':'i', 'Ã':'A', 'ã':'a'},
nonWord = /\W/g,
mapping = function (c) {
return map[c] || c;
};
return values.replace(nonWord, mapping).toLowerCase();
});
Handlebars.registerHelper('align', function(index) {
return index % 2 === 0 ? '' : 'right';
});
// foreach
Handlebars.registerHelper("foreach", function (arr, options) {
if (options.inverse && !arr.length) {
return options.inverse(this);
}
return arr.map(function (item, index) {
item.$index = index;
item.$first = index === 0;
item.$last = index === arr.length - 1;
return options.fn(item);
}).join('');
});
Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) {
switch (operator) {
case '==':
return (v1 == v2) ? options.fn(this) : options.inverse(this);
case '===':
return (v1 === v2) ? options.fn(this) : options.inverse(this);
case '<':
return (v1 < v2) ? options.fn(this) : options.inverse(this);
case '<=':
return (v1 <= v2) ? options.fn(this) : options.inverse(this);
case '>':
return (v1 > v2) ? options.fn(this) : options.inverse(this);
case '>=':
return (v1 >= v2) ? options.fn(this) : options.inverse(this);
case '&&':
return (v1 && v2) ? options.fn(this) : options.inverse(this);
case '||':
return (v1 || v2) ? options.fn(this) : options.inverse(this);
default:
return options.inverse(this);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment