Dealing with an empty list in mustache.js

After struggling for half a day with this problem, I’ve finally found an easy solution!

Don’t check for the list, but check if its first item is not empty!

Template:

{{#persons.0}}
<h2>Persons:</h2>
<ul>
  {{#persons}}
    <li>{{name}}</li>
  {{/persons}}
</ul>
{{/persons.0}}
{{^persons.0}}No persons{{/persons.0}}

Data:

{
  "persons":[
    {"name": "max"},
    {"name": "tom"}
  ]
}

Output:

<h2>Persons:</h2>
<ul>
  <li>max</li>
  <li>tom</li>
</ul>

Data:

{
  "persons": []
}

Output:

"No Persons"

Leave a Comment