Mike Robinson Mike Robinson - 1 year ago 216
Javascript Question

Logical operator in a handlebars.js {{#if}} conditional

Is there a way in handlebars JS to incorporate logical operators into the standard handlebars.js conditional operator? Something like this:

{{#if section1 || section2}}
.. content

I know I could write my own helper, but first I'd like to make sure I'm not reinventing the wheel.

Answer Source

This is possible by 'cheating' with a block helper. This probably goes against the Ideology of the people who developed Handlebars.

Handlebars.registerHelper('ifCond', function(v1, v2, options) {
  if(v1 === v2) {
    return options.fn(this);
  return options.inverse(this);

You can then call the helper in the template like this

{{#ifCond v1 v2}}
    {{v1}} is equal to {{v2}}
    {{v1}} is not equal to {{v2}}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download