首页 > 解决方案 > 如何将百里香片段作为参数传递给另一个片段?

问题描述

是否可以将标签/片段传递给另一个模板thymeleaf

示例:我想创建一个基本tableview布局,调用者模板应该只提供<tbody>应该注入到 tableview 模板布局中的内容。

这可能是表格布局:

<div th:fragment="tableview (tbodyFragment)">
    <table class=...>
        <thead>...</thead>

        <!-- the table body should be repaced -->
        <tbody th:replace="${tbodyFragment}"/>
    </table>
</div>

调用模板:

<tbody id="tbodyFragment">
    <th:block th:each="row : ${rows}">
        <tr>
            <td th:text="${row.id}"/>
            <td th:text="${row.firstname}"/>
            <td th:text="${row.lastname}"/>
            <td th:text="${row.age}" style="text-align:right"/>
        </tr>   
    <th:block>
</tbody>

<div th:insert="~{tableview::tableview(tbodyFragment)}"/>

当然上面的语法是无效的,但你明白了。我怎么能做到这一点?

标签: javathymeleaf

解决方案


这很简单,将片段作为 id 传递,并将其嵌套在th:insert调用模板的标签下方:

<div th:insert="~{tableview::tableview(~{:: #tbodyFragment})}">
   <tbody id="tbodyFragment">
           ...content here...
   </tbody>
</div>

推荐阅读