有条件地关闭 Thymeleaf 中的标签
Conditionally closing tag in Thymeleaf
我需要在我的 Thymeleaf
模板中有条件地关闭标签。比如说,在迭代一些元素集合的过程中,我必须将其中一些元素的系列包装成单个 <div>
:
<div>...element1, element2, element3...</div>
<div>...element4...</div>
<div>...element5, element6...</div>
如果存在某种有条件的标记关闭方式,则可以将其存档。但是我显然不能写</div th:if="...">
。如果它是 jsp
我可以很容易地写出这样的东西:
<%if (condition) {%></div><%}%>
有解决这个问题的想法吗?
EDIT 准确地说,我的 元素 不仅仅是字符串,它们是复杂的内部 html 块。
将条件逻辑上移一层
<body th:each="...">
<div></div>
</body>
查看此处的文档:http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#using-theach
我找到了解决方法。应该包装成单个 <div>
的一系列块应该在模型中表示为单独的列表。比如说,我有 Element
class 来描述我的 element
块。所以,我的模型应该是这样的:
List<Element> elementGroups
我必须为它创建双循环:
<div th:each="group : ${elementGroups}">
<th:block th:each="element : ${group}">
...
</th:block>
</div>
我认为最好将数据表示为单独的列表,正如您在 中提到的那样。
但即使出于好奇,也有一个丑陋的变通方法可以实现与您所问的 <%if (condition) {%></div><%}%>
类似的东西。
诀窍是将标签生成为转义文本:
<th:block th:if="${openTagCondition}" th:utext="'<div>'" />
<th:block th:if="${colseTagCondition}" th:utext="'</div>'" />
这只是出于好奇。我不建议使用此解决方法,因为它很难读,损害可维护性,并且您可以留下不平衡的标签。
我需要在我的 Thymeleaf
模板中有条件地关闭标签。比如说,在迭代一些元素集合的过程中,我必须将其中一些元素的系列包装成单个 <div>
:
<div>...element1, element2, element3...</div>
<div>...element4...</div>
<div>...element5, element6...</div>
如果存在某种有条件的标记关闭方式,则可以将其存档。但是我显然不能写</div th:if="...">
。如果它是 jsp
我可以很容易地写出这样的东西:
<%if (condition) {%></div><%}%>
有解决这个问题的想法吗?
EDIT 准确地说,我的 元素 不仅仅是字符串,它们是复杂的内部 html 块。
将条件逻辑上移一层
<body th:each="...">
<div></div>
</body>
查看此处的文档:http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#using-theach
我找到了解决方法。应该包装成单个 <div>
的一系列块应该在模型中表示为单独的列表。比如说,我有 Element
class 来描述我的 element
块。所以,我的模型应该是这样的:
List<Element> elementGroups
我必须为它创建双循环:
<div th:each="group : ${elementGroups}">
<th:block th:each="element : ${group}">
...
</th:block>
</div>
我认为最好将数据表示为单独的列表,正如您在
但即使出于好奇,也有一个丑陋的变通方法可以实现与您所问的 <%if (condition) {%></div><%}%>
类似的东西。
诀窍是将标签生成为转义文本:
<th:block th:if="${openTagCondition}" th:utext="'<div>'" />
<th:block th:if="${colseTagCondition}" th:utext="'</div>'" />
这只是出于好奇。我不建议使用此解决方法,因为它很难读,损害可维护性,并且您可以留下不平衡的标签。