Mustache - How to detect array is not empty?

て烟熏妆下的殇ゞ 提交于 2019-11-29 02:10:16

问题


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

回答1:


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/




回答2:


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


来源:https://stackoverflow.com/questions/11653764/mustache-how-to-detect-array-is-not-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!