Is there a way in handlebars JS to incorporate logical operators into the standard handlebars.js conditional operator? Something like this:
JavaScript
x
4
1
{{#if section1 || section2}}
2
.. content
3
{{/if}}
4
I know I could write my own helper, but first I’d like to make sure I’m not reinventing the wheel.
Advertisement
Answer
This is possible by ‘cheating’ with a block helper. This probably goes against the Ideology of the people who developed Handlebars.
JavaScript
1
7
1
Handlebars.registerHelper('ifCond', function(v1, v2, options) {
2
if(v1 === v2) {
3
return options.fn(this);
4
}
5
return options.inverse(this);
6
});
7
You can then call the helper in the template like this
JavaScript
1
6
1
{{#ifCond v1 v2}}
2
{{v1}} is equal to {{v2}}
3
{{else}}
4
{{v1}} is not equal to {{v2}}
5
{{/ifCond}}
6