Plus minus kind of calculation and comparison in Ember.js template, handlebars?

Ember.js uses handlebars as its template engine and unlike angular.js templates handlebars doesn’t support doing operational works inside the template. Team Handlebars says that any operational thing should never be a part of your display; hence it’s completely unethical to do operational things in handlebars. Thus you can not do things like {{1 + 1}} or {{#if 1==1}} in handlebars.

Fortunately handlebars provides you way to write or register helpers. Inside those helpers you can put all your logic. So you need to follow the steps below to do any operations in ember’s templates.

  • Register a helper.
  • Write logic inside it with its params.
  • Use the helper in template

Calculations in Ember’s handlebars

Register a helper

Running the above command will register a helper named sum in app/helpers/ folder. If you do not know how ember works you can check our guide to ember.js. So, after registering the helper sum, you can open the file app/helpers/sum.js and modify it like below.

use the registered helper

Now that you have created the helper, you can use that in any template like below.

Instead of digit you can also use your variable and it will behave the same.

other calculations

In case of other calculations like minus, multiplication, divide or any other thing you can register a helper and do your operations inside that helper and use that in templates.

Comparison in Ember’s handlebars

Though we can use if else helpers in ember but the parameter it takes is a boolean value (not boolean actually, it works like plain javascript). So if you try {{#if 1===}} this is going to fail. So all you need to do is to create a helper calls equal (or any other name) and call it.

Equal to condition check

The above is the app/helpers/equal.js file which you will create using ember g helper. The template will look like below.

Below are the helpers for greater than or less than check.

Greater than check

Less than check

So you can create any helper and do all your logical operations there and can use those helpers as functions from your template. If you want to know more about template syntaxes, you can check our brief article on ember templates.

About This Author

Hello! I am Paul Shan, a JavaScript Expert, Full Stack and DevOps Engineer cum Consultant based out of Bengaluru, India.