Java Spring Thymeleaf如何在容器外部使用变量

标签 java spring variables model-view-controller thymeleaf

如何声明一个变量并在其容器外部使用它或中断 foreach 循环?这真让我烦恼!

目标是比较两个列表并在列表匹配时显示内容。

代码:

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

最佳答案

您应该在服务器端执行此实现,使用 thymeleaf 的复杂逻辑是没有意义的。它太难阅读和维护,你不应该用 thymeleaf 来对待它。

因此,您可以将此逻辑移至一个方法,然后使用 spEL 调用该方法,而不是像接下来那样使用它。 .

因此,在循环的顶层类上创建一个方法来搜索该项目:

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

然后你只需在循环内调用此方法即可显示其信息:

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

总之,将逻辑移至 java 而不是 thymeleaf .

关于Java Spring Thymeleaf如何在容器外部使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43685022/

相关文章:

java - 如何在Windows批处理文件中获取Java程序的退出状态

java - 覆盖 Json 对象中的值

spring - 使用问题: Spring AOP vs. AspectJ编织

java - JEE 的 Vaadin 和 Spring 之间如何选择

r - 如何评估 R 中带有变量的表达式?

java - 使用 scriptlet 的缺点?

java - for循环中的多线程

java - Spring web flux WebClient : Connection rest by peers, #block 因错误而终止。在以下站点观察到错误

powershell - 在 for-each 循环中对字符串进行条件格式化

c++ - 解析 GLSL 着色器字符串以在 Android NDK 中查找变量名称