Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf: How to exclude outer tag when using th:each?

The Thymeleaf 2.1.4 official doc demonstrates the for each usage as below:

 <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    ...
 </tr>

It generates one <tr> in each iteration, which is perfect fit in this situation. However in my case I don't need the outer tag (here, <tr>).


My use case is to generating <bookmark> tag in a recursive way, no other tags include, and a <bookmark> tag must contain a name and href attribute.

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<body>

<div th:fragment="locationBookmark(location)">
    <bookmark th:each="map : ${location.subMaps}">
        <bookmark th:name="${map.name}"
                  th:href="'#'+${map.id}" th:include=":: locationBookmark(${map})">
        </bookmark>
    </bookmark>
</div>
</body>
</html>

the including side:

<bookmark th:include="bookmark : locationBookmark(${rootLocation})"/>

Many thanks.

like image 917
July Avatar asked Jun 18 '15 11:06

July


2 Answers

Even if it can be done using th:remove="tag" I would suggest you use th:block

<th:block th:each="map : ${location.subMaps}">
   <bookmark th:name="${map.name}"
        th:href="'#'+${map.id}" th:include=":: locationBookmark(${map})">
    </bookmark>
</th:block>
like image 176
Xipo Avatar answered Sep 22 '22 11:09

Xipo


I figured out how to solve the problem, it's easy, just addth:remove="tag" to the outer tag will do.

like image 39
July Avatar answered Sep 22 '22 11:09

July