Pregunta

Estoy intentando crear un fragmento recursivo en Thymeleaf para producir un menú del lado izquierdo.La arquitectura principal es Spring Boot y estoy pasando un objeto Menú poblado que tiene hijos y demás.El código para el menú se ve así:

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

    private List<MenuItem> children;

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

Y un fragmento de 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>

si tomo el depth codifique, todo parece funcionar bien.Pero con ello obtengo:

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

El propósito de depth El código es para que, opcionalmente, pueda colocar una clase para realizar un seguimiento cuando los elementos del menú son hijos del padre.¿Es posible arreglar el contador de profundidad o hacer algo más para probar si el fragmento ya se ejecutó?En última instancia, sólo quiero un menú recursivo con la parte superior ul sin clase y el niño ulestá teniendo una clase de children.

¿Fue útil?

Solución

Pruebe estos cambios

1.Utilice dos parámetros en fragmento como

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

2.pase la profundidad como

<div th:replace="fragments/submenu :: submenu(menu=${child}, depth=${depth+1})"  />

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top