问题
I need to conditionally close tag in my Thymeleaf template. Say, during iterating some collection of elements I have to wrap series of some of them into single <div>:
<div>...element1, element2, element3...</div>
<div>...element4...</div>
<div>...element5, element6...</div>
This could be archived if some way of conditionally tag closing would exist. But I can't obviously write </div th:if="...">. If it would be jsp I could easily write something like:
<%if (condition) {%></div><%}%>
Any ideas how to solve this issue?
EDIT To be precise, my elements aren't just strings, they are complex inner html blocks.
回答1:
I think it's better represent the data as separate lists, as you mentioned in your previous answer.
But even for curiosity, there is an ugly workaround to achieve something similar to <%if (condition) {%></div><%}%>, as you asked.
The trick is to generate the tag as escaped text:
<th:block th:if="${openTagCondition}" th:utext="'<div>'" />
<th:block th:if="${colseTagCondition}" th:utext="'</div>'" />
This is just out of curiosity. I do not recommend using this workaround as it's pretty unreadable, harms maintainability and you can leave unbalanced tags.
回答2:
I've found the workaround. Series of blocks which should be wrapped into single <div> should be represented as separated lists inside model. Say, it I have Element class which describes my element block. So, my model should be like:
List<Element> elementGroups
and I have to create double loop for it:
<div th:each="group : ${elementGroups}">
<th:block th:each="element : ${group}">
...
</th:block>
</div>
回答3:
move the conditional logic up one layer
<body th:each="...">
<div></div>
</body>
take a look at the documentation here: http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#using-theach
来源:https://stackoverflow.com/questions/36747620/conditionally-closing-tag-in-thymeleaf