我正在尝试在Thymeleaf中创建一个递归片段以生成左侧菜单。核心架构是Spring Boot,我传递的是一个填充的Menu对象,它有子等等。菜单代码如下:
public class MenuItem {
private String displayLabel;
private String actionUri;
private List<MenuItem> children;
// ...getters/setters/etc...
}
Thymeleaf片段定义如下:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Menu</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div th:fragment="submenu (menu)" th:remove="tag">
<ul th:if="${not #lists.isEmpty(menu.children)}" th:class="${#objects.nullSafe(depth, 1) > 1}? 'children'">
<li th:each="child : ${menu.children}">
<span th:if="${#strings.isEmpty(child.actionUri)}" th:text="${child.displayLabel}">Addons</span>
<a th:if="${not #strings.isEmpty(child.actionUri)}" th:href="${child.actionUri}" th:text="${child.displayLabel}">Link Item</a>
<div th:replace="fragments/submenu :: submenu(menu=${child}, depth=depth+1)" th:remove="tag" />
</li>
</ul>
</div>
</body>
</html>
如果我取出depth
代码,一切似乎都运行正常。但有了它,我得到了:
2014-07-30 11:13:00.832 ERROR 45869 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#objects.nullSafe(depth, 1) > 1" (fragments/submenu:9)] with root cause
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
depth
代码的目的是这样我可以选择放入一个类来跟踪菜单项何时是父代的子代。是否可以修复深度计数器或执行其他操作以测试片段是否已经运行?最后,我只想要一个递归菜单,其顶部ul
没有课程,而且ul
的课程有children
。
答案 0 :(得分:0)
尝试这些更改
1.在片段中使用两个参数
<div th:fragment="submenu (menu, depth)" >
2.将深度视为
<div th:replace="fragments/submenu :: submenu(menu=${child}, depth=${depth+1})" />