Can you iterate over a list of Thymeleaf fragments?

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Can you iterate over a list of Thymeleaf fragments?

thymeleaf@saliman.net
I have an application with a standard page layout, and many content templates. Each content template could have one or more content sections that I want to treat as fragments. I'd like to be able to iterate over each fragment and include it separately after putting in formatting divs. The idea is that I don't want each content page to have to know how to nest section and div tags to get the page to format correctly. I've tried the following without success:

layout.html:

  <html xmlns:th="http://www.thymeleaf.org"
          th:fragment="layout(contentFragments)">
  <section class="row-outer-sm"
             th:each="frag,iterStat : ${contentFragments}">
      <div class="container">
          <div class="row justify-content-center">
              <div class="col">
                  <div th:if="${iterStat.first}"
                           th:replace="fragments/messages :: messages">
                      Messages go here
                  </div>
                  <div th:replace="${frag}">
                     Content goes here.
                  </div>
              </div>
          </div>
      </div>
  </section>
  </html>

content.html:

  <html lang="en"
        xmlns:th="http://www.thymeleaf.org"
        th:replace="fragments/layout :: layout(~{:: div.section-content})">
  <div class="section-content">
     Some things for my first section
  </div>

  <div class="section-content">
      Some things for my second section
  </div>
</html>

In this case, I have two divs in the content.html template, but in some pages, the "section-content" divs will be dynamically created with a th:each of its own.  The fragment expression in content.html correctly finds all the divs with the section-content class, but they appear to be passed into layout.html as a single concatenated fragment. Is there any way to get a list of fragments I can use for the "th:each" tag in layout.html?