Spring website layouts SSI with thymeleaf templates

28 06 2014

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:


<div th:fragment="head" style="background-color: red">
	<h3><i>Spring tutorial header</i></h3>


<footer th:fragment="foot" style="background-color: yellow;">
  &copy; 2014 Jacek Milewski from <a href="http://www.looksok.wordpress.com">Looks OK!</a>

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" >
        <title>Spring MVC Example</title>
       	<div th:include="header::head"></div>
        <p>Click <a th:href="@{/greeting}">here</a> to advance to the next page.</p>

        <div th:include="footer::foot"></div>


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

Donate Button with Credit Cards

Thank You!




Give Your feedback:

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: