我想通过作为源传递的json对象在ejs模板中创建树菜单小部件。
现在我在ejs文件中创建了2个递归函数(第一个用于主菜单,第二个用于子菜单元素),但是这种方式不喜欢我。
我没有找到其他优雅的方式来做到这一点。有人可以帮助我吗?
这个问题类似于EJS templates: How to generate an HTML tree structure in the most elegant and handy way
<%
function CreateMenu(obj){
let header = '<div id="header">';
header += '<ul id="leftmenu">';
for (let [key, element] of Object.entries(obj.left_header)) {
if(element.class == 'divider'){
header += '<li class="divider"></li>';
continue;
}
header += '<li>';
let dataRel = element.sub_items.length == 0 ? 'data-rel=foglia' : "";
header += '<a class="'+ element.class +'" href="'+ element.href +'" title="'+ element.title +'" '+ dataRel +' >'+element.text+'</a>';
if(element.sub_items.length > 0) {
header += CreateSubMenu(element.sub_items, 'ul-menu');
}
header += '</li>';
}
header += '</ul>';
header += '<ul id="rightmenu">';
for (let [key, element] of Object.entries(obj.left_header)) {
if(element.class == 'divider'){
header += '<li class="divider"></li>';
continue;
}
header += '<li>';
let dataRel = element.sub_items.length == 0 ? 'data-rel=foglia' : "";
header += '<a class="'+ element.class +'" href="'+ element.href +'" title="'+ element.title +'" '+ dataRel +' >'+element.text+'</a>';
if(element.sub_items.length > 0) {
header += CreateSubMenu(element.sub_items, 'ul-menu');
}
header += '</li>';
}
header += '</ul>';
header += '</div>';
return header;
}
function CreateSubMenu(arrSubMenu, className) {
let submenu = '<ul class="'+className+'">';
for (let [key, subElement] of Object.entries(arrSubMenu)) {
if(subElement.class == 'divider'){
submenu += '<li class="divider"></li>';
continue;
}
submenu += '<li>';
let dataRel = subElement.sub_items.length == 0 ? 'data-rel=foglia' : "";
submenu += '<a class="'+ subElement.class +'" href="'+ subElement.href +'" title="'+ subElement.title +'" '+ dataRel +' >'+subElement.text;
if(subElement.sub_items.length > 0 ) {
submenu += '<span class="ui-icon ui-icon-caret-1-e btn-menu-arrow"></span>';
}
submenu += '</a>';
if(subElement.sub_items.length > 0) {
submenu += CreateSubMenu(subElement.sub_items, 'ul-submenu');
}
submenu += '</li>';
};
submenu += '</ul>';
return submenu;
}
%>
<%- CreateMenu(header) %>