Thymeleaf Layout Fragment
Based on application from this post, I will show how to make the MVC app containing two pages, both
with the same header and footer, but different contents. I will reuse the header and footer HTML code,
to avoid code duplication and follow DRY principle.
What I am going to build
The goal is to have two pages differecing only in body, the header and footer are the same, reused
by SSI (Server Side Include)
Get the source code
The source code for this tutorial you can find here. on the GitHub
Build basic MVC Spring app
You can base it, or copy the code from the tutorial in this post
Create Header and Footer contents
Create two HTML files with header and footer content. Mine will be basic ones:
header.html:
<div th:fragment="head" style="background-color: red">
<h3><i>Spring tutorial header</i></h3>
</div>
footer.html:
<footer th:fragment="foot" style="background-color: yellow;">
© 2014 Jacek Milewski from <a
href="http://www.looksok.wordpress.com">Looks OK!</a>
</footer>
Include
fragments
in
Add header
and
footer
divs
in
your
fragment fromheader.html and footer.html:
your
page,
and
main
include head
and
pages
foot
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" >
<head>
<title>Spring MVC Example</title>
</head>
<body>
<div th:include="header::head"></div>
<h1>Welcome!</h1>
<p>Click <a th:href="@{/greeting}">here</a> to advance to the next
page.</p>
<div th:include="footer::foot"></div>
</body>
</html>
You can do it at any other page you need.
Include or replace?
Here I used th:include, so the header.html was inserted into div element. The other option is
to replace that div entirely with fragment content. You can do it with th:replaceinstead of th:include.
Get the source code
The source code for this tutorial you can find here. on the GitHub
Did
I
help
you?
I manage this blog and share my knowledge for free, sacrificing my time. If you appreciate it and find this
information helpful, please consider making a donation in order to keep this page alive and improve
quality