我正在将一个对象数组传递给 Handlebars 。 我像这样在前端检索它
{{this.comment}}
该对象包含以下内容:
`{
_id: "5c527707e28b4fac758cc674",
sectionId: "2",
comments: [
{
replies: [],
authorAvatarUrl:
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDW3D0Emu0_gpP-tAEGPjW88zSabvpdICv6BaoNLArqY3xB4NA",
authorName: "Jesus Zuñiga Vega",
authorId: "1",
authorUrl: "",
comment: "Test",
id: "72845"
}
]
},
{
_id: "5c5279f2e28b4fac758cc761",
sectionId: "3",
comments: [
{
replies: [],
authorAvatarUrl:
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDW3D0Emu0_gpP-tAEGPjW88zSabvpdICv6BaoNLArqY3xB4NA",
authorName: "Jesus Zuñiga Vega",
authorId: "1",
authorUrl: "",
comment: "Test2",
id: "37940"
}
]
},
{
_id: "5c527ce2e28b4fac758cc887",
sectionId: "1",
comments: [
{
replies: [],
authorAvatarUrl:
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDW3D0Emu0_gpP-tAEGPjW88zSabvpdICv6BaoNLArqY3xB4NA",
authorName: "Jesus Zuñiga Vega",
authorId: "1",
authorUrl: "",
comment: "Hello",
id: "77251"
}
]
}`
请注意,它缺少数组的“[ ]”
我想知道是否可以将数据放入js变量中以在前端使用它,如下所示:
var existingComments = [
{
_id: "5c527707e28b4fac758cc674",
sectionId: "2",
comments: [
{
replies: [],
authorAvatarUrl:
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDW3D0Emu0_gpP-tAEGPjW88zSabvpdICv6BaoNLArqY3xB4NA",
authorName: "Jesus Zuñiga Vega",
authorId: "1",
authorUrl: "",
comment: "Test",
id: "72845"
}
]
},
{
_id: "5c5279f2e28b4fac758cc761",
sectionId: "3",
comments: [
{
replies: [],
authorAvatarUrl:
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDW3D0Emu0_gpP-tAEGPjW88zSabvpdICv6BaoNLArqY3xB4NA",
authorName: "Jesus Zuñiga Vega",
authorId: "1",
authorUrl: "",
comment: "Test2",
id: "37940"
}
]
},
{
_id: "5c527ce2e28b4fac758cc887",
sectionId: "1",
comments: [
{
replies: [],
authorAvatarUrl:
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDW3D0Emu0_gpP-tAEGPjW88zSabvpdICv6BaoNLArqY3xB4NA",
authorName: "Jesus Zuñiga Vega",
authorId: "1",
authorUrl: "",
comment: "Hello",
id: "77251"
}
]
}
];
任何帮助将不胜感激,非常感谢!!!
最佳答案
是的,您可以通过在路由文件中创建助手来实现此目的,如下所示
handlebars = handlebars.create({
helpers: {
assign:function (varName, varValue, options) {
if (!options.data.root) {
options.data.root = {};
}
options.data.root[varName] = varValue;
}
}
})
然后在前端,您可以像这样初始化变量或为其赋值
{{assign 'existingComments' this.coment}}
然后才能访问可以使用
{{@root.existingComments }}
关于javascript - 我如何在前端js变量中使用 Handlebars 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54453660/