Is it possible to nest if/else statements in handlebars templates?
16,571
I believe ifs need a preceding #
Try this.
{{#if address}}
<ul>
<li>address.line1</li>
<li>address.line2</li>
{{#if address.line3}}<li>address.line3</li>{{/if}}
{{#if address.line4}}<li>address.line4</li>{{/if}}
</ul>
{{else}}
No address given
{{/if}}
Author by
Henry Wilson
Software developer primarily working with Javascript. Spent 10 years in .Net land before that...
Updated on July 22, 2022Comments
-
Henry Wilson almost 2 years
I'm wondering if it is possible to nest multiple if/else statements using handlebars? All my attempts so far have resulted in compile errors, what I'd like to do is as follows:
{{if address}} <ul> <li>address.line1</li> <li>address.line2</li> {{if address.line3}}<li>address.line3</li>{{/if}} {{if address.line4}}<li>address.line4</li>{{/if}} {{else}} No address given {{/if}}
Is what I'm attempting here achievable? It always results in parser errors, thusfar I've got around it by writing a helper to deal with spitting out the address (which deals with conditionality of line3/line4 in javascript):
{{if address}} {{formatAddress address}} {{else}} No address given {{/if}}
While this works, it would be nice not to have to write a helper function for every instance of this sort of simple conditionality.
-
dcodesmith almost 11 yearsPleasure's mine @HenryWilson :)