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

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

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

  • What Is Plagiarism? How to Avoid It and Cite Sources
  • Microservices for Machine Learning
  • Microservice Madness: Debunking Myths and Exposing Pitfalls
  • Stabilizing ETL Pipelines With Airflow, Presto, and Metadata Contracts
  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.

By 
Mohamed Sanaulla user avatar
Mohamed Sanaulla
·
Nov. 29, 17 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
57.7K 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

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • 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
  • [email protected]

Let's be friends: