Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a ternary operator in handlebars.js?

Tags:

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

like image 975
shawnXiao Avatar asked Aug 11 '12 15:08

shawnXiao


People also ask

How do you use ternary Handlebars?

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... .

Does js have ternary operator?

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.

Is there else if in Handlebars?

Handlebars supports {{else if}} blocks as of 3.0. 0. Show activity on this post.


3 Answers

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")}}
like image 126
Chris Avatar answered Sep 29 '22 11:09

Chris


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.

like image 10
dignifiedquire Avatar answered Sep 29 '22 11:09

dignifiedquire


this works for me

{{#if final}} "Final" {{^}} "Interim" {{/if}}
like image 3
humkins Avatar answered Sep 29 '22 11:09

humkins