问题描述
我正在尝试在我的网站中实施 Mikado template engine,已经实施了 Mustache.js,我期待一个非常简单的过渡,因为 Mikado 接缝基于它,但我想念如何循环遍历数据中的嵌套数组。
使用Mustache.js,是否可以这样做:
{{# data.textuals_section.textuals}}
{{textual_h}}
{{/ data.textuals_section.textuals}}
或者在 Handlebars.js 中,应该是这样的(从未尝试过):
{{#each data.textuals_section.textuals}}
{{textual_h}}
{{/each}}
在 Mikado 中,当然不是,因为 {{# }}
保留用于传递 HTML 标记,并且文档接缝仅引用单级数组,所以我无法理解如何使用 Mikado 进行循环,
不仅如此,在 Mikado 中,嵌套数组接缝甚至无法通过以下语法访问
{{data.textuals_section.textuals.textual_h}}
非常感谢,贝!
解决方法
您必须创建一个新模板并添加每一行。
html
<div id="root"></div>
<template id="subtext">
<div>
<h3>{{data.textual_h}}</h3>
<h4>{{data.textual_sh}}</h4>
<p>{{data.textual_p}}</p>
</div>
</template>
<template id="basic">
<div>
<h1>{{data.textuals_section.textuals_h}}</h1>
<h2>{{data.textuals_section.textuals_sh}}</h2>
<p>{{data.textuals_section.textuals_p}}</p>
<div id="textuals"></div>
</div>
</template>
javascript
const root = document.getElementById("root");
const template = Mikado.compile("basic");
const view = Mikado(root,template);
const data = [{
textuals_section: {
textuals_h: "A main headers",textuals_sh: "A main sub-headers",textuals_p: "A main pragraph...",textuals: [{
textual_h: "A nested header1",textual_sh: "A nested sub-header",textual_p: "A nested paragraph..."
},{
textual_h: "A nested header2",{
textual_h: "A nested header3",textual_p: "A nested paragraph..."
}
]
}
}];
view.render(data);
const root2 = document.getElementById("textuals");
const template2 = Mikado.compile("subtext");
const view2 = Mikado(root2,template2);
data[0].textuals_section.textuals.forEach(row => view2.add(row))
view2.render();