12

When using a conditional in ember, is it possible to have an OR?

{{#if foo OR bar}}

or

{{#if foo || bar}}

There doesn't seem to be anything on it in the docs.

Kingpin2k
  • 47,277
  • 10
  • 78
  • 96
stevenspiel
  • 5,775
  • 13
  • 60
  • 89
  • Ok, looks like here is the answer, if anyone is looking http://stackoverflow.com/questions/16589624/evaluate-two-conditions-in-handlebar-using-ember – stevenspiel Jul 17 '14 at 18:03

3 Answers3

16

You should move the logic to your controller

App.SomeController = Em.Controller.extend({
  foo: true,
  bar: false,

  fooOrBar: Em.computed.or('foo', 'bar')
});

Leaving the template logic to a minimum

{{#if fooOrBar}}
Kingpin2k
  • 47,277
  • 10
  • 78
  • 96
14

Use https://github.com/jmurphyau/ember-truth-helpers:

ember install ember-truth-helpers

Then you can say

{{#if (or foo bar)}}

Depending on your perspective, Kingpin2k's answer is a bit out of date. Previously, the community's understanding was that templates should be largely free of logic. Overtime, our viewpoint has shifted towards putting more declarative logic in templates-- ember-composable-helpers is a great example of this.

Community
  • 1
  • 1
Max Wallace
  • 3,609
  • 31
  • 42
-2

You can create a custom Handlebar helper function to check for conditional operators.

Ember.Handlebars.registerHelper('ifCond', function (temp_v1, operator, temp_v2, options) {
var v1,v2;
v1 = Ember.Handlebars.get(this, temp_v1, options);
v2 = Ember.Handlebars.get(this, temp_v2, options);    
switch (operator) {
    case '||':
        return (v1 || v2) ? options.fn(this) : options.inverse(this);
    case '&&':
        return (v1 && v2) ? options.fn(this) : options.inverse(this);
    case '==':
        return (v1 == v2) ? options.fn(this) : options.inverse(this);
    default:
        return options.inverse(this);
}
});

You can call it in your templates as

{{#ifCond foo '||' bar}}
    <div>Conditional helpers works </div>
{{/ifCond}}
Jeevi
  • 1,052
  • 1
  • 10
  • 22
  • This won't work in ember handlebars, it doesn't support block helpers. – Kingpin2k Jul 17 '14 at 18:17
  • @kingpin2k What i have given is Custom Handlebar Helpers. It can be used in ember handlebars and it will work. Kindly check the jsbin - http://emberjs.jsbin.com/copos/1/ – Jeevi Jul 17 '14 at 18:28
  • Doesn't work, it only works the first time, try changing one of the values, it won't recalculate, http://jsbin.com/xijoreya/1/edit – Kingpin2k Jul 17 '14 at 18:35
  • I have given example for custom ifCondition to check in your template you can add all operators like ( &&, ||, ==, ===, !=, !==, <, <=, >, >=). Have a common method to check for any condition in your template. Here it will not recalculate. Thanks for pointing. – Jeevi Jul 17 '14 at 18:41