admin管理员组文章数量:1356377
I have this nested Array of Objects:
var tree = [
{
name: "item 1",
link: "#link-1",
children: [
{
name: "item 1.1",
link: "#link-11",
children: [
{
name: "item 1.1.1",
link: "#link-111",
children: []
}
]
},
{
name: "item 1.2",
link: "#link-12",
children: []
}
]
},
{
name: "item 2",
children: []
}
];
I would like to generate an HTML ul
li
tree structure from this model.
The only solution I found is just below (via a recursive function). But I would like to avoid string concatenation, because in my real situation I have more markup to add on each rows of li
(and this is really not handy).
<%
var markup = '';
function htmlTreeBuilder(items) {
if (items.length) {
markup += '<ul>';
}
for (var i = 0; i < items.length; i++) {
markup += '<li>';
markup += '<a href="' + items[i].link + '">' + items[i].name + '</a>';
// Children
htmlTreeBuilder(items[i].children);
markup += '</li>';
}
if (items.length) {
markup += '</ul>';
}
}
htmlTreeBuilder(tree);
%>
<%- markup %>
I have this nested Array of Objects:
var tree = [
{
name: "item 1",
link: "#link-1",
children: [
{
name: "item 1.1",
link: "#link-11",
children: [
{
name: "item 1.1.1",
link: "#link-111",
children: []
}
]
},
{
name: "item 1.2",
link: "#link-12",
children: []
}
]
},
{
name: "item 2",
children: []
}
];
I would like to generate an HTML ul
li
tree structure from this model.
The only solution I found is just below (via a recursive function). But I would like to avoid string concatenation, because in my real situation I have more markup to add on each rows of li
(and this is really not handy).
<%
var markup = '';
function htmlTreeBuilder(items) {
if (items.length) {
markup += '<ul>';
}
for (var i = 0; i < items.length; i++) {
markup += '<li>';
markup += '<a href="' + items[i].link + '">' + items[i].name + '</a>';
// Children
htmlTreeBuilder(items[i].children);
markup += '</li>';
}
if (items.length) {
markup += '</ul>';
}
}
htmlTreeBuilder(tree);
%>
<%- markup %>
Share
Improve this question
asked Feb 16, 2014 at 0:17
EtienneEtienne
2,2873 gold badges28 silver badges45 bronze badges
1 Answer
Reset to default 11I found a better approach, but it need a separate EJS file.
In my main.ejs
:
<%- partial('treeView', {items: tree}) %>
In the treeView.ejs
:
<% if (items.length) { %>
<ul>
<% } %>
<% items.forEach(function(item){ %>
<li>
<a href="<%= item.link %>"><%= item.name %></a>
<%- partial('treeView', {items: item.children}) %>
</li>
<% }) %>
<% if (items.length) { %>
</ul>
<% } %>
本文标签:
版权声明:本文标题:javascript - EJS templates: How to generate an HTML tree structure in the most elegant and handy way - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744032750a2579215.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论