How to use fragments in Thymeleaf

It’s fairly common for any file to have duplication in the code, and the problem is usually solved by defining reusable components.

The same is the case with layout pages in Thymeleaf, which can have a lot of repeated HTML snippets.

Thymeleaf has fragments, which are basically reusable snippets of HTML. Fragments are very similar to methods; just as we use methods to better structure our code in Java, we use fragments to better structure HTML pages.

How to define a fragment

We can define fragments with the following keyword in any of the HTML tags:

th:fragment

To define a fragment in a div tag, use the code shown below:

<div th:fragment="myfragment">
  <div>
  </div>
</div>

Here, myfragment is the name of the fragment. The nested div is the content of the fragment.

Layout composed of fragments

Usage of fragments

Let’s define a fragment called divider:

<div th:fragment="divider">
  <div>
  </div>
</div>

Suppose this fragment is placed in a file called fragments.html. We can reference the specific divider fragment using the following syntax:

~{filename :: fragmentname}

Let’s use the fragment in our layout file like so:

<div>
  <div>There is some content here.
  </div>
  <div th:insert="~{fragments :: divider}">
  </div> 
  <div> There's more content here.
  </div>
</div>

By using th:insert, Thymeleaf will insert the content of the fragment as a child of the declared tag, which is div in this case. The th:insert attribute expects a fragment expression, which is defined by the ~{...} syntax.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved