In this tutorial, you will learn how to create reusable html / javascript component in Thymeleaf. It is always good to keep our code DRY (Don’t Repeat Yourself), so making some common reusable parts for site where we can use it in different pages or files. Learn more about thymeleaf.

How to use Fragments in Thymeleaf - Spring Boot

Thymeleaf is a template engine. It is a modern server-side Java template engine for both web and standalone environments. Allows HTML to be correctly displayed in browsers and as static prototypes. Here you can find simple Spring Boot MVC Project with Thymeleaf Dependency.

Pagination in Spring Boot using Thy...
Pagination in Spring Boot using Thymeleaf - Spring Boot Tutorial

Maven Dependencies


Gradle Dependencies

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

Simple Controller

public String homePage() {
    return "index.html";

Fragments in Thymeleaf

It is recommended to keep all fragments in a folder. Inside resources/templates create a folder with name fragments. We will create a fragment for header section with name header-fragment.html

<title>Thymeleaf Fragment Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="[email protected]/dist/js/bootstrap.bundle.min.js"></script>

Now we can insert the above header-fragment.html in our index.html

<!DOCTYPE html>
<html lang="en">
  <head th:insert="fragments/header-fragment.html"> </head>

<div class="container-fluid p-5 bg-primary text-white text-center">
  <h1>My Site</h1>
  <p>Simple example of fragments</p> 


If you notice above HTML. we have inserted fragment in head tag with th:insert. If you are not using keeping fragments folder, you can keep path without folder name – th:insert="header-fragment.html"

Fragment Inclusion Tags

There are three basic ways to include content from a fragment:

  • insert – inserts content inside the tag
  • replace – replaces the current tag with the tag defining the fragment
  • include – this is deprecated but it may still appear in a legacy code

Replace fragment Tag Example

<!-- header-fragment.html -->
<title>Simple Title</title>
<!-- menu-fragment.html -->
  <li>About Us</li>

Now we can insert the above menu-fragment.html in our index.html

<!DOCTYPE html>
<html lang="en">
  <head th:insert="fragments/header-fragment.html"> </head>
  <div th:replace="fragments/menu-fragment.html"></div>

Above if you see, we use th:replace. This will replace the div tag as well. In th:insert content is added inside the tag.