Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Handlebars If helper.
Handlebars.registerHelper("if", function (expression, options) {
try {
if (expression.split(' ').length == 1 && (!/@(\w+)/.test(expression))) {
if (options.data.root[expression] && !!(options.data.root[expression])) {
return (options.data.root[expression]) ? options.fn(this) : options.inverse(this);
} else {
return options.inverse(this);
}
} else {
return Handlebars.helpers["x"].apply(this, [expression, options]) ? options.fn(this) : options.inverse(this);
}
} catch (e) {
if (!(/ReferenceError/.test(e))) {
console.warn("{{#if " + expression + "}} hit an error:", e);
}
}
});
Handlebars.registerHelper("unless", function (expression, options) {
try {
if (expression.split(' ').length == 1 && (!/@(\w+)/.test(expression))) {
if (options.data.root[expression] && !(options.data.root[expression])) {
return (options.data.root[expression] !== 'true') ? options.fn(this) : options.inverse(this);
} else {
return options.fn(this);
}
} else {
return (!Handlebars.helpers["x"].apply(this, [expression, options])) ? options.fn(this) : options.inverse(this);
}
} catch (e) {
if (!(/ReferenceError/.test(e))) {
console.warn("{{unless " + expression + "}} hit an error:", e);
}
}
});
Handlebars.registerHelper("x", function(expression, options) {
var fn = function() {},
decMatch,
result;
decMatch = /@(\w+)/g.test(expression);
if (decMatch) {
expression = expression.replace(/@(\w+)/g, '$1');
}
with (decMatch ? options.data : options.data.root) {
try {
result = eval(expression);
} catch (e) {
if (!(/ReferenceError/.test(e))) {
console.warn("{{x " + expression + "}} hit an error:", e);
}
}
}
return result;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment