如何递归地使用百里香叶渲染菜单 [英] How to render menu using thymeleaf recursively
问题描述
我想使用ul / li列表呈现HTML菜单。我有这个类结构:
I would like to render HTML menu using ul/li list. I've got this class structure:
public class MenuItem {
private String name;
private MenuItem parent;
private List<MenuItem> children;
public MenuItem(String name,List<MenuItem> children) {
this.name = name;
this.children = children;
for (MenuItem child : children) {
child.parent = this;
}
}
public MenuItem(String name) {
this.name = name;
}
public String getName() {
return name;
}
public MenuItem getParent() {
return parent;
}
public List<MenuItem> getChildren() {
return children;
}
}
正如你所看到的那样,它是典型的树形结构,其中一个根元素包含对其子元素的引用,并且它们引用了它们等等。
As you can see it's typical tree structure, in which one root element contains reference to its children and they have reference to theirs and so on.
现在我想渲染这样的结构:
Now I would love to render structure like this:
<ul>
<li>Item 1
<ul>
<li>Item 1.1</li>
<li>Item 1.2
<ul>
<li>Item 1.2.1</li>
<li>Item 1.2.3</li>
</ul>
</li>
<li>Item 1.3</li>
</ul>
</li>
<li>Item 2</li>
</ul>
如何用百里香做到这一点?如果我必须使用其他技术,比如Tiles,Layout或其他任何东西,我很容易。
How can I do that with thymeleaf? I'm easy if I have to use other technologies like Tiles, Layout or anything else.
编辑:我尝试过参数化包含/替换但是没有运气。传递的参数将转换为String,不能用于其他级别的递归。请参阅 https://github.com/ultraq/thymeleaf-layout-dialect/issues / 12
I tried parameterized include/replace but with no luck. Parameters passed through are converted to String and can't be used for another level of recursion. See https://github.com/ultraq/thymeleaf-layout-dialect/issues/12
非常感谢,
Frank
推荐答案
试试这个:
为单个菜单项创建一个片段为 menuFragment .html
Create a fragment for single menu item as menuFragment.html
<html>
<section layout:fragment="menu">
<ul>
<li th:each="menuItem : ${menuItemsList}" th:text="${menuItem.name}">
<section layout:include="@{path/to/folder/menuFragment} :: menu" th:with="menuItemsList=${menuItem.children}"></section>
</li>
</ul>
</section>
</html>
将片段包含在菜单文件中
Include the fragment in your menu file as
<section layout:include="@{path/to/folder/menuFragment} :: menu" th:with="menuItemsList=${rootMenuItemAsList}"></section>
rootMenuItemAsList
是包含父菜单的列表
希望这个帮助你
这篇关于如何递归地使用百里香叶渲染菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!