Search code examples
springspring-mvcconditional-statementsthymeleaf

Conditionally closing tag in Thymeleaf


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.


Solution

  • 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>