Mustache render list if not empty

user737751 picture user737751 · Oct 25, 2012 · Viewed 11.2k times · Source

I would like to use Moustache to render an HTML unordered list only if a list object is not empty. So I would like:

<ul>
    <li>item 1</li>
    <li>item 2</li>
</ul>

if the list has elements and nothing if the list is empty (not even ul tags)

How can I do this?

edit: my data structure is:

{ "list": ["first item", "second item"] }

Answer

broox picture broox · Oct 17, 2013

If you don't want to or can't reformat your data, you can also just check items.length before rendering the <ul> tags. Some people frown upon this, but it's definitely an alternative to Mike's answer.

{{#items.length}}
    <ul>
        {{items}}
            <li>{{property}}</li>
        {{/items}}
    </ul>
{{/items.length}}