Pergunta

Estou tentando criar um fragmento recursivo no Thymeleaf para produzir um menu do lado esquerdo.A arquitetura principal é Spring Boot, e estou passando um objeto Menu preenchido que possui filhos e coisas assim.O código do menu é semelhante a:

public class MenuItem {
    private String displayLabel;
    private String actionUri;

    private List<MenuItem> children;

    // ...getters/setters/etc...
}

E um fragmento Thymeleaf definido como:

<!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) &gt; 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>

Se eu pegar o depth código, tudo parece funcionar bem.Mas com isso eu consigo:

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

O propósito do depth o código é para que eu possa opcionalmente colocar uma classe para rastrear quando os itens de menu são filhos do pai.É possível corrigir o contador de profundidade ou fazer outra coisa para testar se o fragmento já foi executado?Em última análise, eu só quero um menu recursivo com o topo ul não ter aula e a criança ulestá tendo uma aula de children.

Foi útil?

Solução

Experimente essas mudanças

1. Use dois parâmetros no fragmento como

<div th:fragment="submenu (menu, depth)" >

2. Passe a profundidade conforme

<div th:replace="fragments/submenu :: submenu(menu=${child}, depth=${depth+1})"  />
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top