Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine th:each with templating element using Thymeleaf

I have a list of 'product' which I want to show as a list of row table using an html template.

The html template looks like:

<tr th:fragment="productTemplate">
    <td th:text="${productName}">product name</td>
    <td th:text="${productprice}>product price</td>
</tr>

Here is what I did:

<table>
  <tr th:each="product : ${products}" th:substituteby="product :: productTemplate" th:with="productName=*{name}, productPrice=*{price}" />
</table>

If I use th:include, there will be tr nested to each tr If I use th:substituteby, substitute has the priority on th:each

I cant find a way to replace my loop items by an other.

Somebody have a solution to do this?

like image 316
fliim Avatar asked May 29 '13 16:05

fliim


1 Answers

I got it:

<table>
  <tr th:each="product : ${products}" th:include="product :: productTemplate" 
      th:with="productName=${product.name}, productPrice=${product.price}" 
      th:remove="tag" />
</table>

And here, we can keep the template class on the tr element (that what I wanted)

<tbody th:fragment="productTemplate">
  <tr class="my-class">
    <td th:text="${productName}">product name</td>
    <td th:text="${productPrice}">product price</td>
  </tr>
</tbody>

here's the result:

<table>
  <tr class="my-class">
    <td>Lettuce</td>
    <td>12.0</td>
  </tr>
  <tr class="my-class">
    <td>Apricot</td>
    <td>8.0</td>
  </tr>
</table>

thanks to danielfernandez from the official thymeleaf forum

like image 167
fliim Avatar answered Nov 11 '22 16:11

fliim