Conditionally closing tag in Thymeleaf

做~自己de王妃 提交于 2020-01-02 18:27:08

问题


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="'&lt;div&gt;'" /> 

<th:block th:if="${colseTagCondition}" th:utext="'&lt;/div&gt;'" /> 

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!