Check for a value equals to in Ember Handlebar If block helper

Solution 1:

The {{#if}} helper can only test for properties, not arbitrary expressions. The best thing to do in cases like this is therefore to write a property computing whatever conditional you want to test for.

personIsJohn: function() {
  return this.get('person') === 'John';
}.property('person')

Then do {{#if personIsJohn}}.

Note: If you find this too limiting, you can also register your own more powerful if helper.

Solution 2:

Use an Ember.Component, thus avoid repetitively defining computed properties in your classes (like personIsJohn above):

// if_equal_component.js script
App.IfEqualComponent = Ember.Component.extend({
  isEqual: function() {
    return this.get('param1') === this.get('param2');
  }.property('param1', 'param2')
});

// if-equal.handlebars template
{{#if isEqual}}
  {{yield}}
{{/if}}

You can define the else part of the comparison, with an App.ElseEqualComponent:

// else_equal_component.js script
App.ElseEqualComponent = App.IfEqualComponent.extend();

// else-equal.handlebars template
{{#unless isEqual}}
  {{yield}}
{{/unless}}

Usage:

{{#if-equal param1=person param2="John"}}
  Hi John!
{{/if-equal}}
{{#else-equal param1=person param2="John"}}
  Who are you?
{{/else-equal}}

Solution 3:

If you're using HTMLBars (Ember version 1.10+), then you can use the Ember Truth Helper addon:

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

Once installed, it'll be as simple as this:

{{#if (eq person "John")}} hello {{/if}}

Solution 4:

although this problem can be solved using eq helper by writing

{{#if (eq person "John")}} hello {{/if}}

but for a general solution you can make your own helper which will take three params param[0] and param[2] being operand and param[1] being operator. Below is the helper file.

compare.js

import Ember from 'ember';

export function compare(params) {
  if(params[3]){  //handle case insensitive conditions if 4 param is passed.
    params[0]= params[0].toLowerCase();
    params[2]= params[2].toLowerCase();
  }
  let v1 = params[0];
  let operator = params[1];
  let v2 = params[2];
  switch (operator) {
    case '==':
      return (v1 == v2);
    case '!=':
      return (v1 != v2);
    case '===':
      return (v1 === v2);
    case '<':
      return (v1 < v2);
    case '<=':
      return (v1 <= v2);
    case '>':
      return (v1 > v2);
    case '>=':
      return (v1 >= v2);
    case '&&':
      return !!(v1 && v2);
    case '||':
      return !!(v1 || v2);
    default:
      return false;
  }
}

export default Ember.Helper.helper(compare);

now you can easily use it for multiple purpose.

for equality check.

{{#if (compare person '===' 'John')}} {{/if}}

for greater check.

{{#if (compare money '>' 300)}} {{/if}}

and so on.