Ответ 1
Используйте th:remove="tag"
. (документация)
фрагменты/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>
Допустим, у меня есть два шаблона Thymeleaf:
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>
фрагменты/main.html:
<!DOCTYPE html>
<html>
<head></head>
<body>
<div th:fragment="content">
<p>This is the main content.</p>
</div>
</body>
</html>
Как я могу запретить Tymeleaf включать div
который определяет фрагмент в композитный вывод? То есть, как мне заставить Thymleaf сгенерировать следующий вывод:
<!DOCTYPE html>
<html>
<head></head>
<body>
<header>foo</header>
<section>
<p>This is the main content.</p>
</section>
<footer>bar</footer>
</body>
</html>
Вместо:
<!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>
Используйте th:remove="tag"
. (документация)
фрагменты/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>
В качестве альтернативы, вы можете попробовать использовать th:block
вместо div
в main.html
, вот так:
<!DOCTYPE html>
<html>
<head></head>
<body>
<th:block th:fragment="content">
<p>This is the main content.</p>
</th:block>
</body>
</html>
Однако обратите внимание, что это немного изменит main.html
вид main.html
при просмотре в виде необработанного HTML без предварительной обработки Thymeleaf.
Еще один простой способ добиться этого - использовать th:replace="fragments/main :: content/text()">
как показано здесь: https://github.com/thymeleaf/thymeleaf/issues/451
Ваши фрагменты/main.html остаются прежними
Изменения атрибута th:replace
в index.html:
<!DOCTYPE html>
<html>
<head></head>
<body>
<header>foo</header>
<section>
<div th:replace="fragments/main :: content/text()"></div>
</section>
<footer>bar</footer>
</body>
</html>
Возможно, этот метод не был доступен 5 лет назад, когда был задан вопрос, но я хотел бы добавить его сюда для всех, кто сталкивается с этим вопросом в поисках решения. У меня была похожая проблема, и th:remove="tag"
не работал для меня.