【发布时间】:2019-01-19 13:27:05
【问题描述】:
我有一个 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 Code 来写下我想要实现的目标
<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>
【问题讨论】:
标签: javascript html node.js handlebars.js express-handlebars