Skip to content

Instantly share code, notes, and snippets.

@tniswong
Last active December 19, 2015 06:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tniswong/5910264 to your computer and use it in GitHub Desktop.
Save tniswong/5910264 to your computer and use it in GitHub Desktop.
Handlebars ifTest helper. Allows for javascript condition evaluations. http://jsfiddle.net/YsteK/
Handlebars.registerHelper('ifTest', function(expression, options) {
var evalStr = '',
context = [options.data, options.hash];
if(Object.prototype.toString.call(this) == '[object Object]') {
context.push(this);
} else {
context.push({ that: this });
}
for(var x = 0; x < context.length; x++) {
for(var key in context[x]) {
evalStr += 'var ' + key + '=' + JSON.stringify(context[x][key]) + ';';
}
}
evalStr += expression.replace(/@/g, '').replace(/this/g, 'that');
try {
if(!eval(evalStr)) {
return options.inverse(this);
} else {
return options.fn(this);
}
} catch(e) {
console.error(e + "\n\nThe variable may be outside of this context. Did you forget to add it to the hash? i.e. {{#ifTest 'obj > 1' obj=../obj}}");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment