In Handlebars, is there a ternary operator? I don't mean if else
; I mean like a == true ? "a" : "b"
.
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... .
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
Handlebars supports {{else if}} blocks as of 3.0. 0. Show activity on this post.
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")}}
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.
this works for me
{{#if final}} "Final" {{^}} "Interim" {{/if}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With