¿Utilizar una plantilla de Thymeleaf sin incluir el elemento de definición de fragmento?

StackOverflow https://stackoverflow.com//questions/22023890

  •  21-12-2019
  •  | 
  •  

Pregunta

Digamos que tengo dos plantillas de Thymeleaf:

índice.html:

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

fragmentos/main.html:

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

¿Cómo evito que Tymeleaf incluya el div ¿Eso define el fragmento en la salida compuesta?Es decir, ¿cómo consigo que Thymleaf genere el siguiente resultado?

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

En lugar de:

<!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>
¿Fue útil?

Solución

Usar th:remove="tag". (documentación)

fragmentos/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>

Otros consejos

Alternativamente, puedes intentar usar th:block en lugar de div en main.html, al igual que:

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

Tenga en cuenta, sin embargo, que esto cambiará ligeramente la forma main.html se ve cuando se ve como HTML sin procesar sin preprocesamiento por parte de Thymeleaf.

Otra forma sencilla de lograr esto es usar th:replace="fragments/main :: content/text()"> como se muestra aquí: https://github.com/thymeleaf/thymeleaf/issues/451

Su fragmentos/main.html sigue siendo el mismo

El th:replace cambios de atributos en el índice.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>

Quizás este método no estaba disponible hace 5 años cuando se formuló la pregunta, pero quería agregarlo aquí para cualquiera que se encuentre con esta pregunta y busque una solución.Estaba teniendo un problema similar y el th:remove="tag" no funcionó para mí.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top