Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

376
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!