gpt4 book ai didi

jquery - Mustache.js 中的条件循环

转载 作者:行者123 更新时间:2023-12-03 22:28:36 26 4
gpt4 key购买 nike

如何输出<hr>在每次迭代之后,除了最后一次使用 Mustache.js 的迭代。我尝试了 javascript for 循环,但无法摆脱最后 <hr> 。 (有些人建议使用handlebars.js,但我想保留 mustache 。)

这是我的 json(随着添加更多员工,列表会变得更大)

    {
employees: [
{firstName: "John", lastName: "Smith"},
{firstName: "John", lastName: "Doe"},
{firstName: "Jane", lastName: "Doe"}
]
}

我想要这个 html 输出:

John Smith
<hr>
John Doe
<hr>
Jane Doe

最佳答案

查看Mustache Manual ,您将需要使用所谓的“倒置部分”。来自手册:

An inverted section begins with a caret (hat) and ends with a slash. That is {{^person}} begins a "person" inverted section while {{/person}} ends it.

While sections can be used to render text one or more times based on the value of the key, inverted sections may render text once based on the inverse value of the key. That is, they will be rendered if the key doesn't exist, is false, or is an empty list.

要利用此功能,您可以向最后一个员工添加一个额外的属性来区分它。

JSON:

{
"employees": [
{"firstName": "John", "lastName": "Smith"},
{"firstName": "John", "lastName": "Doe"},
{"firstName": "Jane", "lastName": "Doe", "last": true}
]
}

mustache 模板:

{{#employees}}
{{firstName}} {{lastName}}
{{^last}}
<hr />
{{/last}}
{{/employees}}

这与 Mustache Demo 非常相似展示,使用颜色数组中第一个对象的“first”属性。

关于jquery - Mustache.js 中的条件循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9089517/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com