pusle
pusle

Reputation: 1513

Show boolean values in Handlebars

Trying to learn Ember JS, and I am a complete beginner.

I have an Ember JS application where a model has a boolean value. When I show this value in Handlebars, I do it like this:

{{#if user.active}}Yes{{else}}No{{/if}}

What I am not sure of is if this is the correct way to do it? Should I create a helper? Is there some other "best practice" way of doing this?

The model looks like this:

import DS from 'ember-data';
export default DS.Model.extend({
    id: DS.attr('integer'),
    name: DS.attr('string'),
    email: DS.attr('string'),
    location: DS.attr('string'),
    active: DS.attr('boolean'),
    administrator: DS.attr('boolean')
});

I am thankful for all the pointers I can get :)

Upvotes: 0

Views: 2233

Answers (2)

locks
locks

Reputation: 6577

A shorter alternative is to use the inline version of the if helper, like this:

{{if user.active 'Yes' 'No'}}

Let's reference the Writing Helpers official documentation to implement the helper.

You can get started by running ember generate helper is-user-active in your terminal. Replace is-user-active with the name that you want.

Then, open app/helpers/is-user-active.js and change the code to:

import Ember from 'ember';

export function isUserActive([user]) {
  return user.get('active') ? 'Yes' : 'No';
}

export default Ember.Helper.helper(isUserActive);

After saving, you can start using this helper like so: {{is-user-active user}}.

[edit: localization]

To support localization using ember-i18n (see comments), we will need to use the i18n service provided by the addon. In order to use it, we need to change our helper to use the Class-based helper syntax:

import Ember from 'ember';

export default Ember.Helper.extend({
  i18n: Ember.inject.service(),

   compute([user], hash) {
    let isUserActive = user.get('active');

    if (isUserActive) {
      return this.get('i18n').t('user.active');
    } else {
      return this.get('i18n').t('user.notActive');
    }
  }
});

user.active and user.notActive are made up keys, you'll need to substitute for your own. The i18n service documentation has an example of passing data for interpolation, if necessary.

Upvotes: 4

SomeUnusedUsername
SomeUnusedUsername

Reputation: 172

A helper would be a simple and clean solution

// Helper
Handlebars.registerHelper("printBool", function(b) {
  if (b) {
    return "Yes";
  } else {
    return "No";
  }
});

// Usage 
{{printBool user.active}}

Upvotes: 0

Related Questions