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.
Here we have vanilla handlebars for multiple logical && and || (and or):
Not so sure if it's "safe" to use "and" and "or"... maybe change to something like "op_and" and "op_or"?
Unfortunately none of these solutions solve the problem of "OR" operator "cond1 || cond2".
Use "^" (or) and check if otherwise cond2 is true
{{#if cond1}} DO THE ACTION {{^}} {{#if cond2}} DO THE ACTION {{/if}} {{/if}}
It breaks DRY rule. So why not use partial to make it less messy
I can understand why you would want to create a helper for situations where you have a large number of varied comparisons to perform within your template, but for a relatively small number of comparisons (or even one, which was what brought me to this page in the first place), it would probably just be easier to define a new handlebars variable in your view-rendering function call, like:
Pass to handlebars on render:
and then within your handlebars template:
I mention this for simplicity's sake, and also because it's an answer that may be quick and helpful while still complying with the logicless nature of Handlebars.
Here's an approach I'm using for ember 1.10 and ember-cli 2.0.
Then you can use it in your templates like this:
Where the arguments to the expression are passed in as
p0
,p1
,p2
etc andp0
can also be referenced asthis
.In Ember.js you can use inline if helper in if block helper. It can replace
||
logical operator, for example:One problem with all of the answers posted here is that they don't work with bound properties, i.e. the if condition is not re-evaluated when the properties involved change. Here's a slightly more advanced version of the helper supporting bindings. It uses the bind function from the Ember source, which is also used to implement the normal Ember
#if
helper.This one is limited to a single bound property on the left-hand side, comparing to a constant on the right-hand side, which I think is good enough for most practical purposes. If you need something more advanced than a simple comparison, then perhaps it would be good to start declaring some computed properties and using the normal
#if
helper instead.You can use it like this: