How to use Handlebars ternary helper?
Asked Answered
A

3

13

Following this answer, I wrote a helper like

module.exports.register = function (Handlebars) {
    Handlebars.registerHelper('ternary', function(test, yes, no) {
        return test ? yes : no;
    });
};

I'm certain that the helper is loaded and being defined but can't figure out the syntax to use it. I tried using it like

<div>{{ternary(true, 'yes', 'no')}}</div>

but that gives an assemble build error

Warning: Parse error on line 10:
...<div>{{ternary(true, 'yes',
----------^
Expecting 'ID', 'DATA', got 'INVALID' Use --force to continue.

What is the proper syntax to use a helper like that?

Aspect answered 3/4, 2015 at 23:36 Comment(0)
D
16

Handlebars helpers: http://handlebarsjs.com/#helpers don't follow the JavaScript syntax in the templates. You can use them like this:

<div>{{ternary true "yes" "no"}}</div>
Dissidence answered 5/4, 2015 at 16:57 Comment(0)
D
6

Update 7/14/2017

Since both string are considered as truthy value in JavaScript, I have changed my code to the following:

{{input value=email placeholder="Enter Email" class="form-control"
    disabled=(if isResetting 1 0)
}}

============================

Original Answer

How about trying to use inline if {{if}}?

{{if user.isAdmin "True" "False" }}
Dyna answered 6/10, 2016 at 23:51 Comment(0)
R
3

This worked for me, based on the documentation:
https://handlebarsjs.com/guide/builtin-helpers.html#if

{{#each langs }}
    <a 
        class="navbar-item {{#if active}}is-active{{else}}{{/if}}" 
        href="#{{code}}"
    >
        {{label}}
    </a>
{{/each}}
Reviviscence answered 13/7, 2020 at 13:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.