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 楼答案
您应该在服务器端执行此实现,在
thymeleaf
中使用复杂的逻辑是没有意义的。读取和维护太难了,您不应该在thymeleaf
中处理它因此,您可以将此逻辑移动到一个方法,然后使用
spEL
调用该方法,而不是像next那样使用它因此,在循环的顶层类上创建一个搜索该项的方法:
然后在循环中调用此方法以显示其信息:
总之,将逻辑移到java而不是
thymeleaf