Comparison helper for Handlebars.js
13th February 2014 | by Adam Beres-Deak | javascript, templating, handlebars
Personally, I was always missing some sort of comparison helper in Handlebars.js. I know, I know, it's sort of being against the philosophy of Handlebars - being logicless. But I still wanted to have it.
Comparing two variables almost like in plain JavaScript
Thankfully I found a similar question on Stack and a superb answer from a user called Jim.
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);
case '||':
return (v1 || v2) ? options.fn(this) : options.inverse(this);
default:
return options.inverse(this);
}
});
Here is how one would use it:
{{#ifCond value "===" value2}}
Values are equal!
{{else}}
Values are different!
{{/ifCond}}
Update
As Eugene Mirotin pointed out, this solution could be much DRYer, so here is an improved variant of the code which does the same thing:
(function() {
function checkCondition(v1, operator, v2) {
switch(operator) {
case '==':
return (v1 == v2);
case '===':
return (v1 === v2);
case '!==':
return (v1 !== v2);
case '<':
return (v1 < v2);
case '<=':
return (v1 <= v2);
case '>':
return (v1 > v2);
case '>=':
return (v1 >= v2);
case '&&':
return (v1 && v2);
case '||':
return (v1 || v2);
default:
return false;
}
}
Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) {
return checkCondition(v1, operator, v2)
? options.fn(this)
: options.inverse(this);
});
}());
Latest blog posts
Displaying icons with custom elements 14th October 2015
Plain JavaScript event delegation 26th January 2015
After the first year of blogging - what happened on my blog in 2014? 1st January 2015
Better webfont loading with using localStorage and providing WOFF2 support 18th December 2014