我正在尝试使用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>如果我的数据结构如下所示:
我希望能得到:
<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>有人能发现为什么这不起作用吗?
发布于 2015-04-21 19:24:18
问题的原因是
您正在尝试th:text,并试图将描述添加到<li>中,同时也试图在相同的标记<li>中对片段进行th:include。
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>
...https://stackoverflow.com/questions/29728842
复制相似问题