conditional class for html using pure handlebars
I registered a helper to do this, to keep things cleaner, and in case there were more classes to add.
/**
* Prints an objects key if the value is true.
* example: {printed:true, pleaseprint:'hello', notprinted:false, noprint:undefined}
*/
handlebars.registerHelper("printif", function(object){
// stringToPrint:boolean
var out = [];
for (var string in object) {
var value = object[string];
if (false===value || null===value || undefined===value) {
continue;
}
out.push(string);
}
return out.join(' ');
});
And the template:
<div class="module {{printif moduleVars}}">
The variable:
var moduleVars = {"align-right":isRTL}
So if isRTL is true, it will output the string:
<div class="module align-right">
It is not necessary to wrap around entire HTML elements. You can just wrap the class
with the if
clause.
<p dir="auto" {{#if isRTL}}class="align-right"{{/if}}>{{{content}}}</p>
This will render the class="align-right"
attribute only if isRTL
is truthy.
Also, as Handlebars is an extension of Mustache you could use:
<p dir="auto" {{#isRTL}}class="align-right"{{/isRTL}}>{{{content}}}</p>
With a helper i achieved clean. But in my case condition was two variables truthiness.
//js
Handlebars.registerHelper('ternary', function(cond, v1, v2) {
return cond ? v1 : v2;
});
//html
<p dir="auto" class="some-other-class {{ternary isRTL 'align-right' 'align-left'}}">{{{content}}}</p>