简体   繁体   中英

ember if or statement

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 .

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}}

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.

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}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM