Use a Thymeleaf template without including the fragment definition element?

James Sumners picture James Sumners · Feb 25, 2014 · Viewed 16.4k times · Source

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>

Answer

Iwo Kucharski picture Iwo Kucharski · Feb 25, 2014

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>