Skip to content Skip to sidebar Skip to footer

Is There A Ternary Operator In Handlebars.js?

In Handlebars, is there a ternary operator? I don't mean if else; I mean like a == true ? 'a' : 'b'.

Solution 1:

The if helper can be used as a ternary operator by passing three arguments to it.

In the following example, a button has a default value of "Save Changes", but when model.isSaving is true, then the value temporarily changes to Saving....

<button>{{if model.isSaving "Saving...""Save Changes"}}</button>

...alternatively, used within another helper:

{{inputtype="submit" value=(if model.isSaving "Saving...""Save Changes")}}

Solution 2:

You can build your own helper in handlbars if you really want to. Something like ternary(a==true, "a", "b"). For more information on that see the documentation. The idea from m90 is not the idea behind handlebars. The idea is to not have explicit code in your templates, only calls to helpers and objects.

Solution 3:

I have a helper for this (pay attention that other helpers can also be used inside) https://gist.github.com/terion-name/d87ed8907f1bb2e25f32

// app/helpers/iftrue.js
import Ember from'ember';

export function iftrue(params) {
  if (params[0]) {
    returnparams.length === 2 ? params[0] : params[1];
  }
  if (params.length === 2) {
    returnparams[1];
  } elseif (params.length === 3) {
    returnparams[2];
  }
  returnnull;
}

export default Ember.Helper.helper(iftrue);

With two parameters: if first parameter evaluates to true it will be printed, otherwise second

{{iftrue project.price 'N/A'}} // $9.99
{{iftrue project.priceNotAvailable 'N/A'}} // N/A

With three parameters: if first parameter evaluates to true second will be printed, otherwise third

// If deadline isset formatted date will be printed, otherwise 'N/A'
{{iftrue project.deadline (moment-format project.deadline 'DD.MM.YYYY') 'N/A'}} 

Solution 4:

This below code can be used for ternary or any kind of expression eval.

Warning: please use this code in scenario where eval can be used safely.

{{#if (myfunc "(a[0] + 1) % 2 === 0" arg1)}}

{{/if}}

{{#if (myfunc "(a[0] + a[1]) % 2 === 0" arg1 arg2)}}

{{/if}}

handlebar helper function

myfunc: (exp, ...a) => {
    returneval(exp);
  } 

Solution 5:

this works for me

{{#iffinal}} "Final" {{^}} "Interim" {{/if}}

Post a Comment for "Is There A Ternary Operator In Handlebars.js?"