简体   繁体   中英

Mustache - conditionally render a list from array data

I've got an existing app which uses Mustache.js for templating and I'm needing to conditionally render a list from array data (json) coming from the server. Is this possible with Mustache?

Some example data:

"Preferences": ["pref-red", "pref-blue"]

Easy enough to output that via:

<ul class="plain">
    {{#Preferences}}
    <li>{{.}}</li>
    {{/Preferences}}
</ul>

But what I really want to do is conditionally render the appropriate parts of a static list based on whatever preferences data comes back. Some really dumb psuedo code:

<ul class="plain">
    {{#Preferences}}
        {{if pref-red}}<li class="icon red bell">Red</li>{{/if}}
        {{if pref-green}}<li class="icon green car">Green</li>{{/if}}
        {{if pref-blue}}<li class="icon blue cat">Blue</li>{{/if}}
        {{if pref-yellow}}<li class="icon yellow flower">Yellow</li>{{/if}}
        {{if pref-purple}}<li class="icon purple house">Purple</li>{{/if}}
    {{/Preferences}}
</ul>

Which would in this case output in the browser as:

<ul class="plain">
    <li class="icon red bell">Red</li>
    <li class="icon blue cat">Blue</li>
</ul>

I know Mustache doesn't have if conditions, but can this be achieved in Mustache? I'd like to keep it to Mustache if possible (reduce, reuse, recycle).

No, it can not be achieved by Mustache with your raw data as it is.

Your two options:

  • Transform your input data so that it can be rendered by Mustache.
  • Change rendering engine. You have yourself added the handlebars.js tag to your question: you already have an answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM