Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a Thymeleaf template without including the fragment definition element?

Tags:

thymeleaf

Let's say I have two Thymeleaf templates:

index.html:

<!DOCTYPE html>
<html>
<head></head>
<body>
<header>foo</header>
<section>
    <div th:replace="fragments/main :: content"></div>
</section>
<footer>bar</footer>
</body>
</html>

fragments/main.html:

<!DOCTYPE html>
<html>
<head></head>
<body>
<div th:fragment="content">
    <p>This is the main content.</p>
</div>
</body>
</html>

How do I prevent Tymeleaf from including the div that defines the fragment in the composited output? That is, how do I get Thymleaf to generate the following output:

<!DOCTYPE html>
<html>
<head></head>
<body>
<header>foo</header>
<section>
    <p>This is the main content.</p>
</section>
<footer>bar</footer>
</body>
</html>

Instead of:

<!DOCTYPE html>
<html>
<head></head>
<body>
<header>foo</header>
<section>
    <div>
        <p>This is the main content.</p>
    </div>
</section>
<footer>bar</footer>
</body>
</html>
like image 519
James Sumners Avatar asked Sep 05 '25 03:09

James Sumners


2 Answers

Use th:remove="tag". (documentation)

fragments/main.html:

<!DOCTYPE html>
<html>
<head></head>
<body>
<div th:fragment="content" th:remove="tag">
    <p>This is the main content.</p>
</div>
</body>
</html>
like image 153
Iwo Kucharski Avatar answered Sep 07 '25 22:09

Iwo Kucharski


Alternatively, you could try using th:block instead of div in main.html, like so:

<!DOCTYPE html>
<html>
<head></head>
<body>
<th:block th:fragment="content">
    <p>This is the main content.</p>
</th:block>
</body>
</html>

Note, however, that this will slightly change the way main.html looks when viewed as raw HTML without preprocessing by Thymeleaf.

like image 45
Michał Kosmulski Avatar answered Sep 07 '25 23:09

Michał Kosmulski