Terraform
Terraform

Reputation: 71

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>

Upvotes: 1

Views: 1479

Answers (1)

Pau
Pau

Reputation: 16116

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.

Upvotes: 1

Related Questions