简体   繁体   English

小胡子-有条件地根据数组数据呈现列表

[英]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. 我有一个现有的应用程序,该应用程序使用Mustache.js进行模板制作,并且需要有条件地渲染来自服务器的数组数据(json)的列表。 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). 如果可能的话,我希望将其保留在Mustache中(减少,重复使用,回收)。

No, it can not be achieved by Mustache with your raw data as it is. 不,按原样,Mustache无法实现此目的。

Your two options: 您有两个选择:

  • Transform your input data so that it can be rendered by Mustache. 转换您的输入数据,以便可以由Mustache呈现。
  • Change rendering engine. 更改渲染引擎。 You have yourself added the handlebars.js tag to your question: you already have an answer. 您已经将handlebars.js标记添加到了您的问题:您已经有了答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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