Thymeleaf - pasar variables a fragmentos
Sep 21 2020
Tengo la siguiente plantilla con un fragmento donde paso la variable:
<div th:fragment="main">
<span>
<th:block th:include=" :: inner(${item})" /> </span> <a> <th:block th:include=" :: inner(${item})" />
</a>
</div>
<th:block th:fragment="inner(item)">
[[${item.name}]]
</th:block>
Si trato de renderizarlo, aparece un error que dice:
Property or field 'name' cannot be found on null
Si lo renderizo así
<div th:fragment="main">
<span>
<th:block th:include=" :: inner(${item})" />
[[${item.name}]] </span> <a> <th:block th:include=" :: inner(${item})" />
</a>
</div>
¿Qué estoy haciendo mal al asignar una variable a un fragmento?
Respuestas
michal.jakubeczy Sep 21 2020 at 21:47
Lo averigué.
La razón del error fue que el fragmento 'interno' se renderizó durante el render junto con el fragmento principal. Entonces, junto con las inclusiones, se renderizó por sí mismo. Y este último render lo echó a perder.
Las posibles soluciones son:
- mover el fragmento interior a otro archivo
- agregar
th:if="false"al fragmento 'interno' para evitar la reproducción automática (las inclusiones continuarán funcionando).