Search code examples
javascripthandlebars.jsmustache

how do I omit a line when field is empty (using mustache/handlebars)


i'm currently using mustache and trying to implement some basic if-else checking. In my case, I'm checking for a value in a field.

for example:

I have this JSON data:

"AGENCIES":[
    {
        "IASTATE":"Buenos Aires",
        "IAADDRESS1":"Paraguay 647 Piso 4 Of. 17\/18",
        "IAADDRESS3":"",
        "IALEGALNAME":"Silvia Stocker Australia & New Zealand Travel (ANZ Group)",
        "IACOUNTRY":"Argentina",
        "IAPRINCIPALAGENT":"",
        "IAADDRESS2":"",
        "IAAGENCY":"Australia & New Zealand Group (ANZ Group)",
        "IAEMAIL":"[email protected]",
        "IAPHONE":"+54 11 4311 9828",
        "IAWEBSITE":"http:\/\/www.anzgroup.com.ar\/education-105",
        "IACITY":"Buenos Aires",
        "IALOCATIONHEAD":"Cecilia Minzio"
    },
    {
        "IAAGENCY":"CW International Education",
        "IAADDRESS1":"Juan Francisco Segui 3967",
        "IAPRINCIPALAGENT":"",
        "IALOCATIONHEAD":"Carola Wober",
        "IACOUNTRY":"Argentina",
        "IACITY":"Buenos Aires",
        "IAPHONE":5.41148010867E11,
        "IAADDRESS2":"Piso 6A",
        "IAWEBSITE":"http:\/\/www.cwinternationaleducation.com",
        "IASTATE":"Buenos Aires",
        "IALEGALNAME":"CW International Education",
        "IAEMAIL":"[email protected]",
        "IAADDRESS3":"Ciduad Autonoma"
    }]

As you can see from the data above, some fields can be empty like address2 but some data will always have a value like agency name or country or website.

so How can I omit a whole "line" when a field is empty? something like:

<h3>{{IAAGENCY}}<h3>
{{if IAADDRESS2 is not empty}}<span>{{IAADDRESS2}}</span><br />{{/if}}
<span>{{IACOUNTRY}}</span><br />
<span>{{IAWEBSITE}}</span>

Thanks


Solution

  • Using handlebars you can just check the length of the said json-value:

    <h3>{{IAAGENCY}}<h3>
    {{#if IAADDRESS2.length}}<span>{{IAADDRESS2}}</span><br>{{/if}}
    <span>{{IACOUNTRY}}</span><br />
    <span>{{IAWEBSITE}}</span>
    

    If the length is 0, it evaluates to false, thus the line is omitted