我有一个具有以下格式的 json。我想使用 Mustache js 在 View 中填充该 json。
Json 格式
渲染json的代码是
render: function () {
var tmplData = self.jsonArrayFull;
var out = Mustache.render(self._dashboardTemplate(), tmplData);
self.element.html(out);
}
_dashboardTemplate: function () {
var template = '<div id="layoutContainer" style="background-color:{{backgroundColor}}"></div>';
return template;
},
我该怎么做?它的渲染为空。请帮忙..
最佳答案
您的问题来自于 tmplData
是一个数组,而不是一个对象,因此当您的模板查找 {{backgroundColor}}
时,它的背景颜色为数组,不存在。
要解决此问题,请选择数组中的第一项传递给 Mustache.render
即:
Mustache.render(self._dashboardTemplate(), tmplData[0])
或者在模板中放入一个循环来渲染每个数组项,例如:
var template = '{{#.}}<div id="layoutContainer" style="background-color:{{backgroundColor}}"></div>{{/.}}';
查看这个问题:Can mustache iterate a top-level array?有关渲染顶级数组的详细信息。
关于javascript - 如何从json渲染mustache js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24776142/