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 your main pages
Add header and footer divs in your page, and include head and foot fragment from header.html and footer.html:
<!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:replace instead 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
Thank You!
I was hoping to have the one below, like the include function in PHP.
header.html
Spring MVC Example
footer.html
Been searching around but it looks like it’s really not possible with Thymeleaf.
header.html
footer.html
Okay, sorry, this is annoying. Replacing the angle brackets with square brackets now to express what I’m trying to say.
header.html
[!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]
footer.html
[div th:include=”footer::foot”][/div]
[/body]
[/html]