Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 {{/if}} 

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

like image 999
Mike Robinson Avatar asked Jan 13 '12 15:01

Mike Robinson


People also ask

What is a logical operator in JavaScript?

The logical OR ( || ) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values. When it is, it returns a Boolean value.

How do you iterate objects in Handlebars?

To iterate over an object with JavaScript and Handlebars. js, we can use the #each keyword. to add the Handlebars script and the template for looping through each entry in data . We use #each this to loop through each array property.

How do you call a function in Handlebars?

To call JavaScript function from Handlebars, we can register a helper. to add a template that uses the printItems helper. Then we create the printItems helper and use it by writing: Handlebars.


1 Answers

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}} {{else}}     {{v1}} is not equal to {{v2}} {{/ifCond}} 
like image 52
Nick Kitto Avatar answered Oct 28 '22 15:10

Nick Kitto