Skip to content

Instantly share code, notes, and snippets.

@motionrus
Created September 4, 2023 12:51
Show Gist options
  • Save motionrus/1f48811c85ba311fdd70bc79ee99ff6d to your computer and use it in GitHub Desktop.
Save motionrus/1f48811c85ba311fdd70bc79ee99ff6d to your computer and use it in GitHub Desktop.
// for detailed comments and demo, see my SO answer here http://stackoverflow.com/questions/8853396/logical-operator-in-a-handlebars-js-if-conditional/21915381#21915381
/* a helper to execute an IF statement with any expression
USAGE:
-- Yes you NEED to properly escape the string literals, or just alternate single and double quotes
-- to access any global function or property you should use window.functionName() instead of just functionName()
-- this example assumes you passed this context to your handlebars template( {name: 'Sam', age: '20' } ), notice age is a string, just for so I can demo parseInt later
<p>
{{#xif " name == 'Sam' && age === '12' " }}
BOOM
{{else}}
BAMM
{{/xif}}
</p>
*/
Handlebars.registerHelper("xif", function (expression, options) {
return Handlebars.helpers["x"].apply(this, [expression, options]) ? options.fn(this) : options.inverse(this);
});
/* a helper to execute javascript expressions
USAGE:
-- Yes you NEED to properly escape the string literals or just alternate single and double quotes
-- to access any global function or property you should use window.functionName() instead of just functionName(), notice how I had to use window.parseInt() instead of parseInt()
-- this example assumes you passed this context to your handlebars template( {name: 'Sam', age: '20' } )
<p>Url: {{x " \"hi\" + name + \", \" + window.location.href + \" <---- this is your href,\" + " your Age is:" + window.parseInt(this.age, 10) "}}</p>
OUTPUT:
<p>Url: hi Sam, http://example.com <---- this is your href, your Age is: 20</p>
*/
Handlebars.registerHelper("x", function(expression, options) {
var result;
// you can change the context, or merge it with options.data, options.hash
var context = this;
// yup, i use 'with' here to expose the context's properties as block variables
// you don't need to do {{x 'this.age + 2'}}
// but you can also do {{x 'age + 2'}}
// HOWEVER including an UNINITIALIZED var in a expression will return undefined as the result.
with(context) {
result = (function() {
try {
return eval(expression);
} catch (e) {
console.warn('•Expression: {{x \'' + expression + '\'}}\n•JS-Error: ', e, '\n•Context: ', context);
}
}).call(context); // to make eval's lexical this=context
}
return result;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment