我正在尝试使用 Thymeleaf 创建递归列表。我正在使用一个简单的 Java 对象来模拟一个节点,该节点具有两个字段,一个描述,然后是一个子节点数组列表。我正在使用以下 HTML/Thymeleaf 来处理结构,但它不会递归迭代到下一个级别。
我的 Java 代码如下所示:
public class Node {
public String description;
public ArrayList<Node> children;
}
我的 Thymeleaf/HTML 代码如下:
<html>
...
<body>
<div th:fragment="fragment_node" th:remove="tag">
<ul th:if="${not #lists.isEmpty(node.children)}" >
<li th:each="child : ${node.children}"
th:text="${child.description}"
th:with="node = ${child}"
th:include="this::fragment_node">List Item</li>
</ul>
</div>
</body>
</html>
如果我的数据结构如下所示:
- 主节点1
- 子节点1
- 子节点2
- 主节点2
- 子节点3
- 子节点4
我希望得到:
<ul>
<li>Main Node 1</li>
<li>
<ul>
<li>Child node 1</li>
<li>Child node 2</li>
</ul>
</li>
<li>Main Node 2</li>
<li>
<ul>
<li>Child node 3</li>
<li>Child node 4</li>
</ul>
</li>
</ul>
但是,我只得到:
<ul>
<li>Main Node 1</li>
<li>Main Node 2</li>
</ul>
谁能看出这可能不起作用的原因?
最佳答案
问题的原因是
您正在尝试 th:text
并尝试将描述添加到 <li>
以及你正在尝试 th:include
同一标签内的片段 <li>
.
你的 th:include
被 th:text
取代作为th:text
默认优先处理。
直接解决你的源代码
.....
<li th:each="child : ${node.children}" th:inline="text" th:with="node = ${child}">
[[${child.description}]]
<ul th:replace="this::fragment_node">List Item</ul>
</li>
.....
即使认为上面的内容会如您所愿,我个人还是在您的 thymeleaf 页面中发现了一些设计问题。
使用片段参数的更好解决方案
...
<ul th:fragment="fragment_node(node)" th:unless="${#lists.isEmpty(node.children)}" >
<li th:each="child : ${node.children}" th:inline="text">
[[${child.description}]]
<ul th:replace="this::fragment_node(${child})"></ul>
</li>
</ul>
...
关于html - Thymeleaf 递归不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29728842/