2013-05-29 61 views
3

我有一个'产品'的列表,我想使用html模板显示为一个行表的列表。合并th:每一个使用Thymeleaf的模板元素

HTML模板的样子:

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

这里是我做过什么:

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

如果我使用th:include,会有TR嵌套到每个tr 如果我使用th:substituteby,替补有优先th:each

我无法找到一种方法来取代我的循环项目由其他。

有人有解决方案来做到这一点?

回答

9

我懂了:

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

而在这里,我们可以保持模板类的TR元素(即我想要的东西)

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

这里的结果:

<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> 

感谢danielfernandez来自official thymeleaf forum

0

th:include就是你要找的东西。下面的代码适用于我。我更喜欢把多个片段放在一个文件中,所以我在这里包含了这些内容。

<table> 
    <tr th:each="product : ${products}" th:include="/fragments/productFragment :: productRow" /> 
</table> 
... 

/fragments/productFragment.html 
... 
<tr th:fragment="productRow"> 
    <td th:text="${product.productName}">product name</td> 
    <td th:text="${product.productPrice}">product price</td> 
</tr> 
...