Fragment in Thymeleaf

What is Fragment In Thymeleaf

Fragments in thyme leaf is a section set apart for reusable purposes in another HTML file. they are separated and reorganized into a single line of code to reuse in another HTML file. The whole idea behind fragments is to make HTML files less congested and readable. hence it is also a means to reduce boilerplate code in our projects. In this article, we will be looking at how to apply fragments in our HTML codes using thyme leaf as an HTML template. An example of a fragment statement in HTML.

<div th:replace="fragment ::header"></div>

Creating Fragment project

First, We need to create a simple maven project in STS4. see below how to create a new project. click on New>> Spring Starter Project and this image below will appear. click next and finish.

Create Controller Class

We have created FragmentDemo above with type maven. We will create a class inside the FragmentDemo package named MainController. The main controller class will be used to map the login page with the port 8080 created in the application. property file. We will create the application. property file later in this article. Let's create the MainController class. In your IDE, Click on project and select New >> select Class, name it Maincontroller.

package FragmentDemo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MainController {

    @GetMapping("/login")
    public String viewLoginPage() {
        return "login";

    }
}

Create Login.html File

We have created a MainController class, now we need to create a login.html page to map the MainController method. Let's create login.html with header, body, and footer contents. In your IDE, Click on the project click new >> select the HTML file, name it login.html

<!DOCTYPE html>
<html xmlns:th="http:www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>jumia express</title>
<link
    href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css"
    rel="stylesheet"
    integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We"
    crossorigin="anonymous">
<script
    src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj"
    crossorigin="anonymous"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div class="container">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <div>
                        <img th:src="@{/images/jumia logo.png}" />
                    </div>
                    <div class="collapse navbar-collapse" id="navbarNav">
                        <ul class="navbar-nav">
                            <li class="nav-item"><a class=nav-link href="">Users</a></li>
                            <li class="nav-item"><a class=nav-link href="">Categories</a></li>
                            <li class="nav-item"><a class=nav-link href="">Brands</a></li>
                            <li class="nav-item"><a class=nav-link href="">products</a></li>
                            <li class="nav-item"><a class=nav-link href="">Customers</a></li>
                            <li class="nav-item"><a class=nav-link href="">Shipping</a></li>
                            <li class="nav-item"><a class=nav-link href="">Orders</a></li>
                        </ul>
                    </div>
                </div>
            </nav>

        </div>
<div class="container">
   <h1 align="center" style="margin-top: 50px;">Body Section</h1>
   <p align="center">Add contenets here.</p>
</div>

<footer class="page-footer font-small blue bg-dark mt-5">
    <div class="footer-copyright text-center py-3">&copy; 2023 Copyright: <a href=""> jumia express.com</a></div>
</footer>    
</body>
</html>

Now we have created the login.html file, we need to create a fragment.html file where we will set apart a section that will hold the <header>, <nav>, and <footer> contents. This will eliminate the boilerplate codes we have in the login.html file. This part the most crucial part of this article.

To implement fragments into our project, We will need to reference <html xmlns:th="http:www.thymeleaf.org"> In the URL of the HTML file, this tag will be used to reference the th: attributes anywhere in our HTML file. Referencing the fragments uses either of the two attributes i.e. th: replace or th: insert

Create Fragment.html file

Now let's create the fragment.html file. In your IDE, Click on the project click new >> select the HTML file, and name it fragment.html.

<!DOCTYPE html>
<html xmlns:th="www.thymeleaf.org">
<head th:fragment="headtag">
<meta charset="ISO-8859-1">
<title>jumia express</title>
<link
    href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css"
    rel="stylesheet"
    integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We"
    crossorigin="anonymous">
<script
    src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj"
    crossorigin="anonymous"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
    <div class="container">
        <div th:fragment="navigation">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <div>
                        <img th:src="@{/images/jumia logo.png}" />
                    </div>


                    <div class="collapse navbar-collapse" id="navbarNav">
                        <ul class="navbar-nav">

                            <li class="nav-item"><a class=nav-link href="">Users</a></li>

                            <li class="nav-item"><a class=nav-link href="">Categories</a></li>

                            <li class="nav-item"><a class=nav-link href="">Brands</a></li>

                            <li class="nav-item"><a class=nav-link href="">products</a></li>

                            <li class="nav-item"><a class=nav-link href="">Customers</a></li>

                            <li class="nav-item"><a class=nav-link href="">Shipping</a></li>

                            <li class="nav-item"><a class=nav-link href="">Orders</a></li>

                        </ul>
                    </div>
                </div>
            </nav>

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

            <footer class="page-footer font-small blue bg-dark mt-5">

                <div class="footer-copyright text-center py-3">
                    &copy; 2023 Copyright: <a href=""> jumia express.com</a>
                </div>

            </footer>

        </div>
</body>
</html>

Referencing Fragment in html file

After creating the fragment.html, take note of the th: attributes <head th:fragment="head tag"> , <div th:fragment="navigation"> and <div th:fragment="footer"> these 3 attributes will be used to reference fragment.html in the login.html file.

Now let's recreate the login.html a file that references the fragment.html file.

<!DOCTYPE html>
<html xmlns:th="http:www.thymeleaf.org">
<head th:replace="fragment ::headtag">
<body>
<div th:replace="fragment ::navigation"></div>    

<div class="container">
   <h1 align="center" style="margin-top: 50px;">Body Section</h1>
   <p align="center">Add dynamic contents...</p>
</div>

<div th:replace="fragment ::footer"></div>    

</body>
</html>

We have been able to shrink our login.html codes into lesser codes, all thanks to fragments from Thymeleaf. Now let's launch our project to see if we still have the same content as expected.

Conclusion

We can all try this out in our various IDE. making your code neat and readable is one of the qualities of a good programmer.

6
Subscribe to my newsletter

Read articles from salami adeniyi adedeji directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

salami adeniyi adedeji
salami adeniyi adedeji