结合:每个都使用Thymeleaf的模板元素

fli*_*iim 4 spring templates java-ee thymeleaf

我有一个'产品'列表,我希望将其显示为使用html模板的行表列表.

html模板看起来像:

<tr th:fragment="productTemplate">
    <td th:text="${productName}">product name</td>
    <td th:text="${productprice}>product price</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

这是我做的:

<table>
  <tr th:each="product : ${products}" th:substituteby="product :: productTemplate" th:with="productName=*{name}, productPrice=*{price}" />
</table>
Run Code Online (Sandbox Code Playgroud)

如果我使用th:include,将会嵌套到每个tr 如果我使用th:substituteby,替换具有优先权th:each

我找不到另一种方法来替换我的循环项目.

有人有解决方案吗?

fli*_*iim 10

我知道了:

<table>
  <tr th:each="product : ${products}" th:include="product :: productTemplate" 
      th:with="productName=${product.name}, productPrice=${product.price}" 
      th:remove="tag" />
</table>
Run Code Online (Sandbox Code Playgroud)

在这里,我们可以将模板类保留在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>
Run Code Online (Sandbox Code Playgroud)

这是结果:

<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>
Run Code Online (Sandbox Code Playgroud)

感谢danielfernandez官方thymeleaf论坛