Mustache templates: How to output a block only once for non-empty lists

前端 未结 3 824
傲寒
傲寒 2020-12-18 21:16

If my list is empty, I want to output this:

If my list i

相关标签:
3条回答
  • 2020-12-18 22:00

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

    {{#items.length}}
        <ul>
            {{items}}
                <li>{{name}}</li>
            {{/items}}
        </ul>
    {{/items.length}}
    
    0 讨论(0)
  • 2020-12-18 22:01

    You could use non-false values of a section. name would have to be an object inside of items

    data = { 'items' : { 'name' : ["Item 1", "Item 2", "etc"] } };
    

    You template would look like:

    <div id="some-id">
        {{#items}}
        <ul>
            {{#name}}
            <li>{{.}}</li>
            {{/name}}
        </ul>
        {{/items}}
    </div>
    

    Here's an example on jsFiddle showing the rendering of an items object with names and without -- http://jsfiddle.net/maxbeatty/fpQwk/

    0 讨论(0)
  • 2020-12-18 22:06

    The other two answers do not work for the Ruby implementation of Mustache. My solution was to send an additional parameter as part of the template context; e.g.

    template = <<EOF
    {{#has_items}}
    <ul>
        {{#items}}
            <li>{{.}}</li>
        {{/items}}
    </ul>
    {{/has_items}}
    EOF
    items = ['one', 'two', 'three']
    context = { items: items, has_items: items.any? }
    Mustache.render(template, context)
    
    0 讨论(0)
提交回复
热议问题