Last active
December 20, 2017 02:59
-
-
Save rickysullivan/2ecdf9b7fcfb2cce320ed1e90074f165 to your computer and use it in GitHub Desktop.
Handlebars If helper.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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