Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to use fragments in Thymeleaf

Yusra Masood

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:


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

<div th:fragment="myfragment">
  <div class="border-dashed">

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 class="border-dashed border-2 border-red-300 mx-4">

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>There is some content here.
  <div th:insert="~{fragments :: divider}">
  <div> There's more content here.

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.




Yusra Masood
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring