gtludwig
gtludwig

Reputation: 5611

Thymeleaf + HTML5 - how to repeat same div throughout the page?

I have a HTML5 page that has (roughly!) the following structure:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
    <form>
    <div id="a">
        <div id="i">
            // content i
        </div>
        <div id="x">
            // some content (several lines of code)
        </div>
     </div>

     <div id="b">
         <div id="j">
             // content j
         </div>
         <div id="x">
             // some content (several lines of code)
         </div>
      </div>

      <div id="c">
          <div id="k">
              // content k
          </div>
          <div id="x">
              // some content (several lines of code)
          </div>
       </div>
    </div>

    // <div id="x" /> definition location

    </form>
</body>
</html>

In order to achieve some ease of maintenance, is it possible to define <div id="x" /> somewhere on the page and call it when needed? Something resembling (but not quite!) a <div th:replace="fragments/x :: xFragment />?

In order to pass its values to the controller, I believe <div id="x" /> should be defined inside the form, say, where on the above code I wrote // <div id="x" /> definition location.

Upvotes: 0

Views: 1437

Answers (1)

crm86
crm86

Reputation: 1394

This is not tested but could be a starting approach:

<div th:fragment="insideFragment(id, id2, content)">
        <div th:id="${id2}">
            <div th:text="${content}" th:remove="tag" />
        </div>
        <div id="x">// some content</div>
</div>

<div th:fragment="myFragment(ids, subids, contents)">

    <th:block th:each="content, i : ${contents}">
    <div th:replace="PATH :: insideFragment(${ids[i.index]}, ${subids[i.index]}, ${content})" />
    </th:block>
</div>

Upvotes: 2

Related Questions