¿Cómo puedo declarar una variable y usarla fuera de su contenedor o romper el bucle foreach ? ¡Esto realmente me está molestando!
El objetivo es comparar dos listas y mostrar cosas si las listas coinciden.
El código:
<tr th:each="listItem : ${list}"> <td th:text="${listItem.getTitle()}"></td> <td th:text="${listItem.getDescription()}"></td> <td> <div th:each="listItem2 : ${list2}"> <div th:if="${listItem.getId()} == ${listItem2.getId()}"> <div th:with="someVariable={true}"> // I want to declare variable and use it after the loop OR break the loop here </div> </div> </div> <div th:if="${someVariable} == true"> // Show stuff </div> </td> </tr>Debe hacer esta implementación en el lado del servidor, no tiene sentido usar esa lógica compleja con thymeleaf , es demasiado difícil de leer y mantener, no debe tratar eso con thymeleaf .
Entonces, en lugar de usarlo como a continuación, puede mover esta lógica a un método y luego llamar al método usando spEL .
Por lo tanto, cree un método en la clase superior del bucle que busque ese elemento:
package com.example public class Item { int id; String title; String description; //and so on //Getters and setters public Item getSubItem(List<Item2> list2) { for(Item2 item2 :list2){ if(this.getId() === item2.getId()) { return item2; } } return null; } }Luego simplemente llama a este método dentro del ciclo para mostrar su información:
<tr th:each="listItem : ${list}"> <td th:text="${listItem.getTitle()}"></td> <td th:text="${listItem. getDescription()}"></td> <td> <div th:if="${listItem.getSubItem(list2)} != null"> //Show stuff </div> </td> </tr> En resumen, mueva su lógica a java en lugar de thymeleaf .