Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

375
Vistas
Java Spring Thymeleaf how to use variable outside container

How can I either declare a variable and use it outside its container or break the foreach loop? This is really bugging me!

The goal is to compare two list and show stuff if the lists match.

The code:

<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>
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You should do this implementation on the server side, it doesn't make sense use that complex logic with thymeleaf it is too difficult to read and maintain, you shouldn't treat that with thymeleaf.

So instead of using it like next, you could move this logic to a method, and then call the method using spEL.

So, create a method on the top class of the loop which searches that item:

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;
    }
}

Then you just call this method inside the loop to show its info:

<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>

In summary, move your logic to java instead of thymeleaf.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda