我有一个传递给我的车把文件的JSON对象。您可以在这里查看此对象
https://jsoneditoronline.org/?id=ea86167f5da7403fbdb6bfaf936bc404
我将JSON文件作为JSON对象传递给hbs文件
router.get('/', (req, res) => {
const jsonFile = fs.readFileSync('treeView.json', 'utf8');
const fileContent = JSON.parse(jsonFile);
res.render('treeView', {
treeView: fileContent
});
});
,然后尝试基于此对象数据创建HTML元素。我试图创建JavaScript-Handlebars-Pseudo代码来写下我想要实现的目标
<div class="folder">
TreeView
<!-- getItems( {{treeView}} ) start with the top level item -->
</div>
<!--
function getItems(currentItem) {
const children = currentItem.children; // try to get all child items
const isFile = !children; // is it a file or a folder?
if (isFile) { // create child container of type "file"
<div class="file">
{{ current.name }}
</div>
} else { // create child container of type "folder"
<div class="folder">
{{ current.name }}
<div class="container">
for (let i = 0; i < children.length; i++) { // recursive call for the children of the current folder
const currentChildItem = children[i];
getItems(currentChildItem);
}
</div>
</div>
}
}
-->
我希望我的示例表明我想创建一个递归调用,该调用将div容器创建为其当前父div的子代。
编辑:
HTML结果为
.folder {
margin-left: 20px;
}
.file {
margin-left: 20px;
}
<div class="folder">
TreeView
<div class="container">
<div class="folder">
Section 1
<div class="container">
<div class="folder">
Section 1.1
<div class="container">
<div class="file">
Section 1.1.1
</div>
<div class="file">
Section 1.1.2
</div>
</div>
</div>
<div class="file">
Section 1.2
</div>
<div class="file">
Section 1.3
</div>
</div>
</div>
<div class="file">
Section 2
</div>
<div class="folder">
Section 3
<div class="container">
<div class="file">
Section 3.1
</div>
<div class="file">
Section 3.2
</div>
</div>
</div>
</div>
</div>
答案 0 :(得分:0)
您可以使用{{#each}}
语句来像这样使用车把进行模板制作:
<div class="folder">
{{treeView.name}}
{{#each treeView.children}}
<div class="container">
{{name}}
{{#if children}}
{{#each children}}
<div class="container">
<div class="file">
{{name}}
{{file}}
</div>
</div>
{{/each}}
{{else}}
<div class="container">
<div class="file">
{{name}}
{{file}}
</div>
</div>
{{/if}}
</div>
{{/each}}
</div>