【问题标题】:How can I render a plain array with mustache.js?如何使用 mustache.js 渲染一个普通数组?
【发布时间】:2018-06-22 15:04:58
【问题描述】:

我正在使用 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 上使用小胡子。

【问题讨论】:

  • 他们的github page{{ . }}。 Mustache 绝对是一种奇怪的模板语言

标签: javascript html json mustache


【解决方案1】:

来自the docs

当遍历一个字符串数组时,一个 .可用于引用列表中的当前项。

查看:

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

模板:

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

输出:

* Athos
* Aramis
* Porthos
* D'Artagnan

【讨论】:

  • 在文档中没有找到它。我暴力破解 x) 谢谢!
【解决方案2】:

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

胡子模板更新

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

【讨论】:

    猜你喜欢
    • 2020-05-06
    • 1970-01-01
    • 2013-05-01
    • 2023-03-05
    • 2014-07-18
    • 2018-11-10
    • 2020-09-10
    • 2021-10-15
    • 1970-01-01
    相关资源
    最近更新 更多