51

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'] }
Anirvan
  • 6,214
  • 5
  • 39
  • 53
Trantor Liu
  • 8,770
  • 8
  • 44
  • 64
  • 2
    Yes, I believe you are going to have to modify the data like you've done with `hasUsers`. Another option is using the more robust [Handlebars](http://handlebarsjs.com/) which handles this exact case on their homepage. – maxbeatty Jul 25 '12 at 18:26

3 Answers3

88

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/

Kara Brightwell
  • 2,529
  • 1
  • 21
  • 29
44

Using {{#users.length}} works great if you want the inner statement to repeat for every element of the array, but if you only want a statement to only run once, you can use:

{{#users.0}}
...
{{/users.0}}
{{^users.0}}
...
{{/users.0}}
Adriano
  • 19,463
  • 19
  • 103
  • 140
dessalines
  • 6,352
  • 5
  • 42
  • 59
1

I'm using chevron for Python. Since {{#users.length}} is implementation-dependent as described in previous answers, and doesn't work for me in Chevron, I return an object in my code which only contains the list if the list is non-empty. Presumably this technique would work for other languages too.

users = ["user1", "user2", "userN"]
user_obj = {"user_list": users} if len(users) > 0 else {}
template = """
{{#users}}
<ul>
    {{#user_list}}
    <li>{{.}}</li>
    {{/user_list}}
</ul>
{{/users}}
"""

chevron.render(template, {"users": user_obj})
Dawngerpony
  • 3,288
  • 2
  • 34
  • 32