DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Migrate, Modernize and Build Java Web Apps on Azure: This live workshop will cover methods to enhance Java application development workflow.

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Kubernetes in the Enterprise: The latest expert insights on scaling, serverless, Kubernetes-powered AI, cluster security, FinOps, and more.

A Guide to Continuous Integration and Deployment: Learn the fundamentals and understand the use of CI/CD in your apps.

Related

  • Getting Started With Thymeleaf In Spring Boot
  • Using JdbcTemplate With Spring Boot and Thymeleaf | Spring Boot Tutorial
  • Spring Beans With Auto-Generated Implementations: How-To
  • Introduction to Spring Boot and JDBCTemplate: JDBC Template

Trending

  • A Comprehensive Approach to Performance Monitoring and Observability
  • Examining Use Cases for Asynchronous APIs: Webhooks and WebSockets
  • Architecture Approach: Domain-Driven Design (DDD)
  • Reading an HTML File, Parsing It and Converting It to a PDF File With the Pdfbox Library
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Boot: Thymeleaf Template Decorator

Spring Boot: Thymeleaf Template Decorator

In this post, we take a look at how you can reuse a header and footer across all Thymeleaf templates with some help from Spring Boot's auto-configuraiton.

Mohamed Sanaulla user avatar by
Mohamed Sanaulla
·
Nov. 29, 17 · Tutorial
Like (7)
Save
Tweet
Share
56.5K Views

Join the DZone community and get the full member experience.

Join For Free

The question of reusing headers and footers on all Thymeleaf templates has been often been asked on StackOverflow. In this article, I will show you how you can structure templates using the Thymeleaf Layout Dialect to achieve a higher code reusability in a Spring Boot application.

Create a Spring Boot Application

Let's use Spring Initializer to create an empty project with the required dependencies. I chose the following for the empty project:

Once you load the project in your favorite IDE, just update the thymeleaf and thymeleaf-layout-dialect version to the following in your project’s pom.xml:

<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>


Note: I have used Spring Boot 1.5.8.RELEASE in this sample.

Defining Base Template

If we are using Spring Boot, we do not have to configure anything to use Thymeleaf and Thymeleaf Layout Dialect. The auto-configuration support will configure all the required beans for using Thymeleaf templates.

Let’s create a base.html at the location src\main\resources\templates:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:th="http://www.thymeleaf.org"   
  xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
  <head>
 
    <title layout:title-pattern="$CONTENT_TITLE - $LAYOUT_TITLE">Base</title>
    <meta name="description" content=""/>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 
    <link rel="stylesheet" type="text/css" 
      href="https://bootswatch.com/4/cerulean/bootstrap.min.css" />
  </head>
  <body>
 
    <nav class="navbar navbar-light bg-light">
      <span class="navbar-brand mb-0 h1">Decorator Sample</span>
    </nav>
 
    <div class="container">
      <nav aria-label="breadcrumb" role="navigation">
        <ol class="breadcrumb">
          <th:block layout:fragment="breadcrumb">
          </th:block>
        </ol>
      </nav>
      <div class="content">
        <div layout:fragment="page_content"></div>
      </div>
    </div>
    <!-- /.container -->
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
    </script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
    </script>
    <th:block layout:fragment="scripts">
    </th:block>
  </body>
 
</html>


In the above base.html, you can see there are three placeholders:

  • Breadcrumbs
  • Content
  • JavaScript required for content

The rest of the Thymeleaf templates decorate using base.html and provide required data for just the three placeholders. Those will be seen in the subsequent sections. The title for the page is defined as layout:title-pattern="$CONTENT_TITLE - $LAYOUT_TITLE" which means that if any template declares a My Page tag, then the page title becomes Base - My Page.

Content for Breadcrumbs

Any page that wishes to decorate itself using base.html should declare in their HTML as shown below:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" 
  xmlns:th="http://www.thymeleaf.org" 
  xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" 
  layout:decorate="~{base}">
</html>


The layout:decorate attribute takes the location of the base template with respect to the templates root folder. In our case, the templates root folder is src/main/resources/templates.

We can provide the content for breadcrumb by writing the following HTML:

<th:block layout:fragment="breadcrumb">
  <li class="breadcrumb-item">Page 1</li>
</th:block>


Ideally, following the order in which the layout:fragment are defined in the base template will help in maintaining consistency in content order among the pages. The final HTML generated by Thymeleaf and its layout dialect is:

<nav aria-label="breadcrumb" role="navigation">
  <ol class="breadcrumb">
    <li class="breadcrumb-item">Page 1</li>
  </ol>
</nav>


Populating the page_content

Along similar lines, the content for page_content will be:

<div layout:fragment="page_content" id="page_content">
  <h3>Page 1</h3>
 
  <div class="alert alert-info" style="display: none;" 
    id="js-content">
  </div>
  <a th:href="@{/page2}">Go to page 2</a>
</div>


Use of <th></th> will remove the need for using a dummy tag just to wrap the content. If we need to wrap the content in a specific element, like we have used <div> above, the <th></th> has to be replaced with the specific element.

Populating the scripts

A few may question the need for the scripts placeholder. This allows us to keep the page-related JavaScript in one place and not pollute all the JavaScript in the base template.

<th:block layout:fragment="scripts">
<script type="text/javascript">
$(function(){
    $("#js-content").html("From Javascript").slideToggle();
});
</script>
</th:block>


You can even create a dedicated .js file and link it in the scripts section:

<th:block layout:fragment="scripts">
<script type="text/javascript"
    src="@{/path/to/js/file}">
</script>
</th:block>


Conclusion

In this article, we saw how to use Thymeleaf Layout Dialect to decorate the templates with a common base template. We didn’t have to do any configuration, as Spring Boot does it via the auto-configuration when relevant libraries are on its classpath, which, in this case, are the dependencies brought in by the starter pom spring-boot-starter-thymeleaf

The working Spring Boot sample can be found here.

Spring Framework Spring Boot Template Thymeleaf

Published at DZone with permission of Mohamed Sanaulla, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Getting Started With Thymeleaf In Spring Boot
  • Using JdbcTemplate With Spring Boot and Thymeleaf | Spring Boot Tutorial
  • Spring Beans With Auto-Generated Implementations: How-To
  • Introduction to Spring Boot and JDBCTemplate: JDBC Template

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: