如何使用 mustache.js 渲染普通数组?

How can I render a plain array with mustache.js?

我正在使用 mustache 进行模板渲染,我遇到了这种情况:

JSON

{
  "header": "Colors",
  "colors": ["red", "green", "blue"]
}

小胡子模板

<h1>{{header}}</h1>
<ul>
{{#colors}}
    <li>{{???}}</li>
{{/colors}}
</ul>

HTML

呈现的HTML应该是

<h1>Colors</h1>
<ul>
    <li>red</li>
    <li>green</li>
    <li>blue</li>
</ul>

{{???}} 应该是什么?到目前为止,我尝试了 {{this}}{{colors}}{{color}} 但没有成功。

您可以在他们的 demo 上留小胡子。

来自the docs

When looping over an array of strings, a . can be used to refer to the current item in the list.

查看:

{
  "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"]
}

模板:

{{#musketeers}}
* {{.}}
{{/musketeers}}

输出:

* Athos
* Aramis
* Porthos
* D'Artagnan

答案是{{.}}!在 Unix 世界中,. 表示当前的、自我的。参见 Dot (command)

小胡子模板已更新

<h1>{{header}}</h1>
<ul>
{{#colors}}
    <li>{{.}}</li>
{{/colors}}
</ul>