0
\$\begingroup\$

I use a Thymeleaf template to inject a set of files (which contain precalculated HTML) into one big HTML. The files with their metadata are stored in a map called files, the files content is stored in another map called content. Both maps share the same key which is basically an id of the files.

The relevant section of the template has these lines:

<div th:each="f : ${files}" th:id="${f.key}">
    <h1 th:text="${f.value.pageTitle}"></h1>
        [(${content[ f.key ]})]
</div>

The result after this template was processed is:

<div id="1">
    <h1>Title of document with ID 1</h1>
    Content of file with ID 1
</div>
<div id="2">
    <h1>Title of document with ID 2</h1>
    Content of file with ID 2
</div>

This works fine but in order to place the th:each I had to introduce a superfluous div. Can I get rid of the div in the template and have a result like this:

<h1>Title of document with ID 1</h1>
Content of file with ID 1
<h1>Title of document with ID 2</h1>
Content of file with ID 2
\$\endgroup\$
  • \$\begingroup\$ Have you tried th:remove="tag" in the div element? thymeleaf.org/doc/tutorials/2.1/… \$\endgroup\$ – aventurin Dec 18 '18 at 22:08
  • \$\begingroup\$ @aventurin This looks promising, I will give it a try. I read the tutorial but overlooked this section. \$\endgroup\$ – Marged Dec 19 '18 at 7:34
  • \$\begingroup\$ @Aventurin I can confirm this is working. Do you want to turn your comment into an answer ? \$\endgroup\$ – Marged Dec 19 '18 at 20:42
  • \$\begingroup\$ @Marget I've added this as an answer. \$\endgroup\$ – aventurin Dec 23 '18 at 14:32
1
\$\begingroup\$

Thymeleaf has a mechanism for removing template fragments. You can use the th:remove="tag" attribute to remove the containing tag but not its children:

<div th:each="f : ${files}" th:remove="tag">
    <h1 th:text="${f.value.pageTitle}"></h1>
    [(${content[ f.key ]})]
</div>

The resulting output will not contain the div but the h1 element and the text node.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.