Mustache - How to detect array is not empty?

Trantor Liu picture Trantor Liu · Jul 25, 2012 · Viewed 21k times · Source

I want to implement the following logic with Mustache:

{{#if users.length > 0}}
    <ul>
        {{#users}}
            <li>{{.}}</li>
        {{/users}}
    </ul>
{{/if}}

// eg. data = { users: ['Tom', 'Jerry'] }

Should I modify the users structure to meet the need? For example:

{{#hasUsers}}
    <ul>
        {{#users}}
            <li>{{.}}</li>
        {{/users}}
    </ul>
{{/hasUsers}}

// eg. data = { hasUsers: true, users: ['Tom', 'Jerry'] }

Answer

Ambarish Chaudhari picture Ambarish Chaudhari · Jul 27, 2013

Sorry, this may be too late. But I had similar requirement and found a better way to do this:

{{#users.length}}
    <ul>
        {{#users}}
            <li>{{.}}</li>
        {{/users}}
    </ul>
{{/users.length}}
{{^users.length}}
    <p>No Users</p>
{{/users.length}}

Working sample here: http://jsfiddle.net/eSvdb/