Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to nest if/else statements in handlebars templates?

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.

like image 685
Henry Wilson Avatar asked Jul 30 '13 11:07

Henry Wilson


People also ask

Is there else if in Handlebars?

Handlebars supports {{else if}} blocks as of 3.0. 0. looking at this again, I feel this can be done through attribute bindings.

How do you compare two values in Handlebars?

{{if}} is used to check whether a field has a value or not, whereas {{compare}} is used to check whether a field has one value or another value. Check out our Handlebars helper reference for more information on handlebars {{compare}}, {{if}}, and other handlebars expressions!

How do you iterate in HBS?

You can iterate over a list using the built-in each helper. Inside the block, you can use this to reference the element being iterated over. You can use the this expression in any context to reference the current context. You can optionally provide an else section which will display only when the list is empty.

What should be the extension for the separate template file?

dwt extension is used to indicate a template.


1 Answers

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}}
like image 191
dcodesmith Avatar answered Oct 24 '22 00:10

dcodesmith