有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaSpringEleaf如何在容器外使用变量

我如何声明一个变量并在其容器外使用它,或者如何中断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>

共 (1) 个答案

  1. # 1 楼答案

    您应该在服务器端执行此实现,在thymeleaf中使用复杂的逻辑是没有意义的。读取和维护太难了,您不应该在thymeleaf中处理它

    因此,您可以将此逻辑移动到一个方法,然后使用spEL调用该方法,而不是像next那样使用它

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

    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