Spring – Thymeleaf iteration Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Spring – Thymeleaf iteration without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Suppose I want to obtain a structure like this:

<div>
  <ul>
    <!-- Item -->
    <li class="item">
      <span class="more no-select" data-target=".item1">+</span>
      <span class="right"></span>
    </li>

    <!-- Children -->
    <li class="item1 hidden nojs">
      <span class="spacing"></span>
      <a href="mylink">My link</a>
    </li>
    <li class="item1 hidden nojs">
      <span class="spacing"></span>
      <a href="mylink">My link</a>
    </li>
    <li class="item1 hidden nojs">
      <span class="spacing"></span>
      <a href="mylink">My link</a>
    </li>
  </ul>
</div>

Basically each item has [0 … n] children.

To obtain this structure using Thymeleaf I’d start by defining the main items as follow:

<li th:each="item : ${items}">
  <span class="more no-select" th:attr="data-target='.' + ${item.id}">+</span>
  <span class="right"></span>
</li>

But then, being that item is limited in scope, how do I cycle through its item.children?

Answer

I think you have to move the th:each to a higher level, so that you can also add the children after each li element. The th:block element should be handy because it itself creates no HTML element but can carry any Thymeleaf attributes.

The outline of the solution should be as follows:

<th:block th:each="item : ${items}">
    <!-- Item -->
    <li class="item">
        item content ...
    </li>
    <!-- Children -->
    <li th:each="child : ${item.children}" class="item1 hidden nojs">
        child content ...
    </li>
</th:block>
We are here to answer your question about Spring – Thymeleaf iteration - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji