How to iterate for items X in Timeleaf?

I have a template where for four li elements I have to have one ul element. How can I do it? 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 the if condition would be applied to the elvery ul element, but it hides everything, including the li element.

+7
thymeleaf
source share
2 answers

According to your comments, you need a list of 4 items, below will be a trick. Let me know if you have a problem.

 <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 consideration based on the data provided provides another opportunity. Use Map instead of bulk lists in the controller before passing it:

 Map<String, List<Excursion>> excursionsList; 

Make sure you limit each excursion to 4 (as needed). Then in Thimeleaf iterate over 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> 

This should clear the heaps of code and make it as needed.

+9
source share

What have I done to achieve what I want. Controller:

 @RequestMapping( "/" ) public String index( Model model ) { List<Excursion> excursions = excursionDao.findAll(); List<List<Excursion>> excursionsLists = new LinkedList<List<Excursion>>(); List<Excursion> tempList = new LinkedList<Excursion>(); int listSize = excursions.size(); for ( int i = 0; i < listSize; i++ ) { tempList.add( excursions.get( i ) ); if ( listSize == ( i+1 ) || tempList.size() == 4 ) { excursionsLists.add( tempList ); tempList = new LinkedList<Excursion>(); } } model.addAttribute( "excursionsLists", excursionsLists ); return "index"; } 

And the thymeleaf pattern:

  <ul th:each="excursionsList : ${excursionsLists}"> <li th:each="excursion : ${excursionsList}"> <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> 
+1
source share

All Articles