Is there a ternary operator in handlebars.js?

Viewed 18919

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

6 Answers

this works for me

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

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);
  } 

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;
}
Related