14

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"] }
  • I believe this is what you're looking for http://stackoverflow.com/questions/10102931/mustache-templates-how-to-output-a-block-only-once-for-non-empty-lists/10118092#10118092 – maxbeatty Oct 26 '12 at 17:47
  • That is an interesting approach, but I was hoping there is a way to do this without modifying my data structure –  Oct 27 '12 at 18:25
  • Could you add your data structure to your question? – maxbeatty Oct 29 '12 at 19:08
  • could be duplicate of https://stackoverflow.com/questions/11653764/mustache-how-to-detect-array-is-not-empty – Adriano Oct 17 '17 at 15:33

2 Answers2

26

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}}
broox
  • 3,538
  • 33
  • 25
10

You need to reformat your data structure to this:

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

Your Mustache template would now be this

{{#list}}
    <ul>
        {{#items}}
            <li>{{.}}</li>
        {{/items}}
    </ul>
{{/list}}

I made a video explaining how Mustache works, and how to implement it using both PHP and JavaScript. You can find it here: http://mikemclin.net/mustache-templates-for-php-and-javascript/

Mike McLin
  • 3,627
  • 7
  • 41
  • 49
  • 10
    It seems kind of unreasonable to ask people to reformat their data structures to accommodate a templating language. – Alper Jan 12 '16 at 11:06
  • 1
    I agree. That's why I personally would choose a different template language. However, if you want to use Mustache, this is how. I like brook's solution better, but I am not sure that the `length` property is always available. I think it might be an enhancement added by the Javascript implementation. I was unable to find any mention of it in the Mustache Manual: https://mustache.github.io/mustache.5.html. – Mike McLin Jan 13 '16 at 18:46
  • It is relatively easy to create a model for the template, deroved from your data stricture but modified as required. This has the advantage that the transformation is performed in code in an actual programming language that is easy to debug. – yeoman Nov 06 '20 at 14:36
  • Complex logic in e.g. Thymeleaf or Angular is exactly what made people yearn something clean and simple. I ageee, though, that pseudovalues "first" and "last" for list elements should be easy to include without making Mustache yet another Velocity or JSP. – yeoman Nov 06 '20 at 14:38