How to do an "if equals" conditional comparison in Handlebars

Handlebars is Ember’s semantic templating engine.

Its nature is to keep logic out of templates, so we’ll run into limitations when implementing certain view-layer logic.

If you ever used the if helper, you have likely tried to do a conditional comparison. For example: “render OK only if the model status equals complete”:

{{#if item.status == "complete"}}

As you may have figured out, this does not work. The if helper can only test for properties to be true or false – not arbitrary expressions.

So how do I compare a model property to something?

The “semantic” answer in this case would be: write an isComplete computed property in the model (or component):

// app/models/item.js

isComplete: Ember.computed('status', function() {
  return this.get('status') == "complete";

// or
isComplete: Ember.computed.equal('status', 'complete')

With the template:

{{#if item.isComplete}}

But this is overkill!

Sometimes sprinkling a little logic in our templates really is the best solution to the problem.

Helpers to the rescue!

I wholeheartedly recommend Ember Truth Helpers which implements many logical/comparison operators.

Here’s how we install it:

$ ember install ember-truth-helpers

Ember Composable Helpers is another fantastic add-on you may find extremely useful in your Ember toolbox.

Our own helper

Alternatively, creating and registering our own eq (equals) helper is super easy:

$ ember generate helper eq

Include our equality function:

// app/helpers/eq.js

import Ember from 'ember';

const eq = (params) => params[0] === params[1];
export default Ember.Helper.helper(eq);

And put it to use!

{{#if (eq item.status "complete")}}

Following this logic you can create similar helpers: gt, lt, or and so on.

Enjoyed this article? Don't miss my next one!

Leave me your e-mail for content that will help you master Ember: