Thymeleaf is a modern, server-side Java template engine for web and standalone environments. It is especially well-suited for rendering HTML, XML, and other markup formats in Spring Boot applications. Thymeleaf integrates seamlessly with Spring Boot to provide a clean, natural templating solution for web applications.
1. Introduction to Thymeleaf
Thymeleaf is a Java-based templating engine used for generating HTML, XML, and other formats. It has several key features that make it popular for web development:
- Natural templating: Thymeleaf templates are designed to be readable in a browser. They resemble the final HTML structure, which makes it easy for designers and developers to collaborate.
- Spring Integration: Thymeleaf is a natural fit for Spring Boot, allowing the use of Spring-specific objects in templates and supporting model data binding.
- Dynamic Content: Thymeleaf provides the ability to create dynamic content by using expressions, conditionals, loops, and more.
- Extensibility: Thymeleaf is highly extensible, allowing developers to create custom tags, dialects, and functionality.
2. Setting Up Thymeleaf with Spring Boot
Spring Boot makes it easy to set up Thymeleaf as a template engine. Here’s a simple guide on how to integrate Thymeleaf with Spring Boot.
2.1. Add Thymeleaf Dependency
Spring Boot provides Thymeleaf integration out-of-the-box. You simply need to include the Thymeleaf dependency in your pom.xml
if you’re using Maven. This dependency is typically included by default when using Spring Boot’s starter templates.
For Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
For Gradle:
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
2.2. Configure Thymeleaf (Optional)
Spring Boot automatically configures Thymeleaf with sensible defaults, but you can customize the configuration by adding properties in the application.properties
or application.yml
file.
Example application.properties
:
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
spring.thymeleaf.prefix
: Defines the location where Thymeleaf will look for templates.spring.thymeleaf.suffix
: Specifies the suffix of the templates, usually.html
.spring.thymeleaf.mode
: Defines the template mode (e.g.,HTML
,XML
).spring.thymeleaf.encoding
: Sets the character encoding.spring.thymeleaf.cache
: Controls whether templates should be cached (for development, set tofalse
).
3. Creating a Simple Thymeleaf Template
Once Thymeleaf is configured, you can start creating templates. Thymeleaf templates are usually placed in the src/main/resources/templates/
directory.
3.1. Create an HTML Template
For example, create a simple index.html
template:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome to Thymeleaf with Spring Boot</h1>
<p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>
In this example:
- The
th:text
attribute is used to replace the content of the<p>
tag with dynamic content. - The
${name}
syntax refers to a model attribute namedname
passed from the Spring Controller.
3.2. Create a Spring Controller
Now, you need to create a Spring controller to pass data to the template.
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("name", "John");
return "index"; // Thymeleaf will search for 'index.html' in the templates folder
}
}
In this example, when the /hello
URL is accessed, Spring Boot will pass the name
attribute with the value "John"
to the Thymeleaf template, and the resulting page will display “Hello, John!”.
4. Running the Application
To run the application, you can either use Spring Boot’s embedded Tomcat server or deploy it to an external server. Here’s how to run it from the command line using Maven:
mvn spring-boot:run
Or, if using Gradle:
./gradlew bootRun
Once the application is running, navigate to http://localhost:8080/hello
in your browser, and you should see the content rendered from the Thymeleaf template.
5. Thymeleaf Syntax and Features
Thymeleaf offers a wide range of syntax and features to make dynamic web pages easy to build.
5.1. Variables and Expressions
- ${…}: Used to refer to variables passed from the controller (e.g.,
${name}
). - #{…}: For message resolution (i.e., internationalization).
- @{…}: For URL resolution (e.g.,
@{/images/logo.png}
).
<p th:text="'Hello, ' + ${username}">Hello, User!</p>
5.2. Conditionals and Loops
Thymeleaf allows you to use standard conditionals and loops directly in the template.
- If-Else Statement:
<div th:if="${user.isActive}">Active User</div>
<div th:unless="${user.isActive}">Inactive User</div>
- For-Each Loop:
<ul>
<li th:each="item : ${items}" th:text="${item.name}"></li>
</ul>
5.3. Fragments and Layouts
Thymeleaf supports reusable templates with fragments. Fragments allow you to define common parts of your templates (e.g., headers, footers) and reuse them across different pages.
<!-- layout.html -->
<div th:fragment="header">
<h1>Welcome to My Site</h1>
</div>
<!-- index.html -->
<div th:replace="~{layout :: header}"></div>
In this example, layout.html
contains a header fragment, and index.html
includes it using th:replace
.
5.4. Forms and Binding
Thymeleaf makes form handling and data binding straightforward. For instance, when you want to bind form fields to an object, you can use the following syntax:
<form th:action="@{/submit}" th:object="${user}" method="post">
<input type="text" th:field="*{username}" />
<input type="submit" value="Submit" />
</form>
In the example above, the form will be bound to a user
object, and the username
field will be automatically populated.