Alex Rivera | Logout

Dealing with an empty list in mustache.js

Asked 2012-01-05T16:15:00.537
34

I'm using mustache.js to render a template in javascript. I'd like to check if a list is empty or not to hide the <h2> tag in the following example. Is this possible or is mustache.js too logic-less?

This is the template:

<h2>Persons:</h2>
<ul>
  {{#persons}}
    {{name}}
  {{/persons}}
</ul>

and this is the data:

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

1 Answer

49

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"
answered 2013-01-19T18:40:00.480

Your Answer