Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

378
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda