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