Is there a ternary operator in handlebars.js?
Asked Answered
T

6

26

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

Tithonus answered 11/8, 2012 at 15:17 Comment(2)
Have you checked the official web-site: handlebarsjs.com? It contains tutorials...Roughdry
I have checked the official web-site.But I didn't see the explaintions of the ternary oprerator.Tithonus
L
11

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.

Lacteous answered 11/8, 2012 at 16:7 Comment(0)
P
22

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:

{{input type="submit" value=(if model.isSaving "Saving..." "Save Changes")}}
Pentacle answered 21/8, 2015 at 18:49 Comment(2)
@majman I've added a code sample to demonstrate what I believe to be the best answer.Laurinelaurita
Does not work for me. Had to resort to {{#if model.isSaving}}"Saving..."{{else}}"Save Changes"{{/if}}Noelyn
L
11

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.

Lacteous answered 11/8, 2012 at 16:7 Comment(0)
K
5

this works for me

{{#if final}} "Final" {{^}} "Interim" {{/if}}
Keto answered 23/4, 2021 at 16:43 Comment(0)
D
1

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]) {
    return params.length === 2 ? params[0] : params[1];
  }
  if (params.length === 2) {
    return params[1];
  } else if (params.length === 3) {
    return params[2];
  }
  return null;
}

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 is set formatted date will be printed, otherwise 'N/A'
{{iftrue project.deadline (moment-format project.deadline 'DD.MM.YYYY') 'N/A'}} 
Demography answered 30/12, 2015 at 18:53 Comment(0)
E
1

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) => {
    return eval(exp);
  } 
Estovers answered 20/11, 2017 at 11:27 Comment(0)
P
0

I guess the built-in if helper used to support use as a ternary operator but no longer does so. I overrode it as follows so it can be used either as a block-helper or ternary operator.

if(...args: any[]) {
    const options = args.pop();
    const {fn} = options;
    if(args.length < (fn ? 1 : 2)) {
        throw new Handlebars.Exception(
            fn ?
                '#if requires exactly one argument' : 
                'if requires two or three arguments'
        );
    }
    let conditional = args.shift();
    if(typeof conditional === 'function')
        conditional = conditional.call(this);
    // Default behavior is to render the positive path if the value is truthy and not empty.
    // The `includeZero` option may be set to treat the condtional as purely not empty based on the
    // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative.
    if ((!options.hash.includeZero && !conditional) || Utils.isEmpty(conditional)) {
        if(fn)
            return options.inverse(this);
        let [, b] = args;
        return typeof b === 'function' ? b.call(this) : b;
    }
    if(fn) return fn(this);
    const [a] = args;
    return typeof a === 'function' ? a.call(this) : a;
}
Patnode answered 12/7, 2022 at 7:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.