【发布时间】:2014-09-22 07:53:26
【问题描述】:
我正在尝试在 Thymeleaf 中创建一个递归片段以生成左侧菜单。核心架构是 Spring Boot,我传入了一个包含子项等的填充菜单对象。菜单代码如下:
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 没有课程,而子 uls 的课程为 children。
【问题讨论】:
标签: spring-boot thymeleaf spring-el