Dealing with an empty list in mustache.js

Max Schmidt picture Max Schmidt · Jan 5, 2012 · Viewed 19.5k times · Source

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"}
  ]
}

Answer

Qazzian picture Qazzian · Jan 21, 2013

You could use persons.length. If it is a truthy value (i.e. greater than 0) then the block will be rendered.

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