Paul S
Paul S

Reputation: 494

Thymeleaf: how to keep count over multipe iterators

I want to keep a global count over multiple iterators in my Thymeleaf template. My model of parents with children looks like this:

val people = listOf(
            Person("p1", listOf(Person("c1"), Person("c2"))),
            Person("p2", listOf(Person("c3"))),
            Person("p3", listOf(Person("c4"), Person("c5"))),
        )

What I have in my template now is this:

<div>
    <h1>Keep count over multiple iterators</h1>
    <div th:each="parent, parentStat : ${model.data.people}">
        <h2 th:text="${parent.name}"></h2>
        <div th:each="child, childStat : ${parent.children}">
            <span th:text="${child.name}"/> (Global count: <span th:text="${childStat.count}"/>)
        </div>
    </div>
</div>

The output looks like this:

Keep count over multiple iterators
p1
c1 (Global count: 1)
c2 (Global count: 2)
p2
c3 (Global count: 1)
p3
c4 (Global count: 1)
c5 (Global count: 2)

Where the global count does not work, obviously, because it is just the count of children of the current parent. (I am only interested in 1 level of parent-child hierarchy).

Is want I want at all possible in Thymeleaf? Or is the only possibility to keep count in the model?

Upvotes: 1

Views: 374

Answers (1)

andrewJames
andrewJames

Reputation: 22032

I do not believe this can be handled using Thymeleaf. If your parents were always guaranteed to have the same number of children, then you could calculate the correct value using something like:

((parent_iteration -1) * children_size) + current_child_count

So, instead, perhaps you can use a CSS counter.

Add the following styles to your page:

body {
    counter-reset: section;                  
}
.countme::before {
    counter-increment: section;
    content: "Child " counter(section) ": ";
}

This includes a countme class definition - which we can then use as follows, whenever we also display a child's name:

<span class="countme"></span><span th:text="${child.name}"></span>

This generates the following output on the web page:

enter image description here

Upvotes: 3

Related Questions