Fragment with overridable parts?

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Fragment with overridable parts?

sparker
Is it possible to define a fragment and when you call that fragment override parts of it?  I tried using something like this:

<div th:fragment="details-table (tableId, bigTable)">
   <div class="table-responsive">
      <tabl th:id="${tableId}"
         class="table table-striped table-condensed table-bordered  dt-responsive simple-data-table"
         cellspacing="0" width="100%" th:attr="data-big-table=${bigTable}">
         <thea th:replace="this :: table-head">
         </thea>
         <tbod th:replace="this :: table-body">
         </tbod>
      </tabl>
   </div>
</div>

when I call this fragment I  want to supply my table head and table body, but use the fragments structure):

<div
   th:include="fragments/details :: details-table (tableId='test-dt', bigTable=${#lists.size(list.records) > 10})">
   <tabl>
      <thea th:fragment="table-head">
         <tr.>
            <th.>Type</th.>
            <th.>Attribute</th.>
         </tr.>
      </thea>
      <tbod th:fragment="table-body">
         <tr. th:each="record : ${list.records}">
            <td. th:text="${record.type}"></td.>
            <td. th:text="${record.attribute}"></td.>
         </tr.>
      </tbod>
   </tabl>
</div>

This works fine as long as I only use this once on a page.  If I call this twice on the same page (I want 2 tables on the same page with different data), the table-body and table-head get combined from both calls in both the table instances.
Reply | Threaded
Open this post in threaded view
|

Re: Fragment with overridable parts?

Metroids
If you are using thymeleaf 3, I think you can accomplish this using fragment expressions.  In this way, you can rename each of your table-head fragments to have unique names and then pass in the name as a fragment expression parameter.

https://github.com/thymeleaf/thymeleaf/issues/451

If you aren't using thymeleaf 3, I think you could also use the layout dialect plugin as it's more suited to this than fragments.

https://github.com/ultraq/thymeleaf-layout-dialect
Reply | Threaded
Open this post in threaded view
|

Re: Fragment with overridable parts?

sparker
Great - Ill take a look, thank you!