Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate for X items in Thymeleaf?

Tags:

thymeleaf

I have the template, where for four li elements I should have one ul element. How should I do this? Now I have something like:

<div th:each="excursion,iterStat : ${excursions}">
    <ul th:if="${iterStat.index}/4 == 0">
        <li>
            <a th:href="@{/excursion/{id}(id=${excursion.excursionId})}"><img src="/template/images/garden1.jpg" alt="Image" /></a>
            <h2 th:text="${excursion.title}"></h2>
            <p th:text="${#strings.abbreviate(excursion.description,128)}"></p>
        </li>
    </ul>
</div>

I thought if condition will be applied to the elvery ul element, but it hide every thing, including li element.

like image 506
Dracontis Avatar asked Nov 23 '14 22:11

Dracontis


People also ask

How do you break the loop in Thymeleaf?

The best solution would be the put this logic in the controller and put the first product of type 'T' in a separate attribute. If that's not possible, another solution would be to write a Thymeleaf extension (or if using Spring a bean) that does this.

What is Th text in Thymeleaf?

The Thymeleaf th:text tag will replace all the text in your h1 tag, that is the reason your output only shows "TITLE". You should place the <small> tags outside your h1 tag.


1 Answers

As per your comments, you needed a list with 4 items, the below will do the trick. Let me know if you got issues

<ul>
<div th:each="excursion,iterStat : ${excursions}" th:if="${iterStat.index}<5">    
        <li>
            <a th:href="@{/excursion/{id}(id=${excursion.excursionId})}"><img src="/template/images/garden1.jpg" alt="Image" /></a>
            <h2 th:text="${excursion.title}"></h2>
            <p th:text="${#strings.abbreviate(excursion.description,128)}"></p>
        </li>    
</div>
</ul>

EDIT 1: Further review based on provided data yields another possibility. Use Map instead of mass lists in Controller before you pass it:

Map<String, List<Excursion>> excursionsList;

Make sure you limit each excursion to 4 (as you require). Then in Thymeleaf iterate through the map.

<div th:each="excursion,rowStat : *{excursionsList}">
<ul>
<div th:each="list,iterStat : *{excursion[__${rowStat.index}__].value}">
//your code for each list item information such as excursionId, description etc.
</div>
</ul>
</div>

That should clean up your code heaps and make it as you need it.

like image 193
Aeseir Avatar answered Nov 01 '22 06:11

Aeseir