gpt4 book ai didi

javascript - 将字符串列表转换为带有 mustache 的 html 列表

转载 作者:行者123 更新时间:2023-11-30 14:15:26 25 4
gpt4 key购买 nike

使用 Mustache 创建列表 works like this :

const Mustache = require('mustache');

let template = `
{{#repo}}
<b>{{name}}</b>
{{/repo}}
`

let context={
repo:[
{name: "John"},
{name: "Lisa"},
{name: "Darth Vader"}
]
}
console.log(Mustache.render(template, context))

它创建:

<b>John</b>
<b>Lisa</b>
<b>Darth Vader</b>

我的问题是:我想直接处理字符串列表。但这似乎与 Mustache 不兼容。如果它不是对象列表,我没有在模板中使用的名称:

// my data is just a list of strings
let my_data = ["a", "b", "c", "d"]

// to make it compatible with Mustache, it has to become a list of objects
let mustache_version=[{el: "a"}, {el: "b"}, {el: "c"}, {el: "d"}]

是否可以使用 Mustache 处理字符串数组?

请注意:我不是在询问如何将数组转换为兼容格式。相反,我想将它按原样提供给 Mustache。

最佳答案

来自 mustache readme :

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

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

Template:

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

所以在你的情况下,你只需要写:

{{#repo}}
<b>{{.}}</b>
{{/repo}}

关于javascript - 将字符串列表转换为带有 mustache 的 html 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53637351/

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