What is a template engine in Spring Boot and how to use it

What is a template engine in Spring Boot and how to use it

In web applications, a templating engine is a tool for dynamically generating HTML, XML, JSON, etc. documents. Spring Boot has built-in a variety of common template engines, such as Thymeleaf, Freemarker, Velocity, etc., allowing us to easily create dynamic web pages.

This article will introduce how to use Thymeleaf, a commonly used template engine in Spring Boot, including how to configure, how to use templates, and how to pass data.

insert image description here

Thymeleaf configuration

Using Thymeleaf in Spring Boot is very simple, just add the following two dependencies to the project's dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>webjars-locator-core</artifactId>
</dependency>

The first dependency above is Spring Boot's Thymeleaf starter, which includes Thymeleaf's required dependencies and automatically configures Thymeleaf's view resolvers. The second dependency is WebJars, which is a tool for managing Web front-end libraries, and we can use it to import Thymeleaf's HTML tag library.

After adding dependencies, we also need to add the following configuration to the configuration file:

# 开启 Thymeleaf 缓存
spring.thymeleaf.cache=true

# Thymeleaf 模板所在的目录,默认为 classpath:/templates/
spring.thymeleaf.prefix=classpath:/templates/

# Thymeleaf 模板文件的后缀,默认为 .html
spring.thymeleaf.suffix=.html

# Thymeleaf 模板文件的编码,默认为 UTF-8
spring.thymeleaf.encoding=UTF-8

# 启用 Thymeleaf 的 HTML 标签库
spring.thymeleaf.mode=HTML

In the above configuration, spring.thymeleaf.cachethe attribute is used to enable Thymeleaf's cache to improve performance. spring.thymeleaf.prefixThe attribute is used to specify the directory where Thymeleaf templates are located, the default is classpath:/templates/. spring.thymeleaf.suffixThe attribute is used to specify the suffix of the Thymeleaf template file, the default is .html. spring.thymeleaf.encodingThe attribute is used to specify the encoding of Thymeleaf template files, and the default is UTF-8. spring.thymeleaf.modeAttribute to enable Thymeleaf's HTML tag library.

After completing the above configuration, we can start using Thymeleaf.

Use of Thymeleaf

Create a template file

First, we need to src/main/resources/templatescreate a Thymeleaf template file in the directory. For example, we create a index.htmltemplate file named as follows:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf Demo</title>
</head>
<body>
    <h1 th:text="${message}">Hello World!</h1>
</body>
</html>

In the template file above, we used Thymeleaf's th:textattribute to dynamically display messages. ${message}Indicates the data passed from the controller, which will be replaced with the actual message content.

create controller

Next, we need to create a controller to handle the request and pass the data to the template. For example, we create a DemoControllercontroller called with the following code:

@Controller
public class DemoController {
    
    
    @GetMapping("/")
    public String index(Model model) {
    
    
        model.addAttribute("message", "Hello Thymeleaf!");
        return "index";
    }
}

In the above controller, we use @Controllerannotations to define a controller that contains a indexmethod for handling GET requests of the root path. In indexthe method, we use Modelthe object to pass data to the template, setting a messageproperty called to Hello Thymeleaf!.

run the program

Finally, we need to start the program and access the root path to see Thymeleaf in action. You can use the built-in web server provided by Spring Boot to run the program, for example, use the following command:

mvn spring-boot:run

After the startup is successful, visit in the browser http://localhost:8080/and you will see the following:

Hello Thymeleaf!

This proves that Thymeleaf has successfully combined templates and data to dynamically generate HTML pages.

Syntax for Thymeleaf

The syntax of Thymeleaf is very simple, it provides tags and expressions similar to JSP. Here are some common Thymeleaf syntaxes:

variable expression

Use ${}the syntax to represent variable expressions, for example:

<h1 th:text="${message}">Hello World!</h1>

In the above example, ${message}it represents the data passed from the controller.

select expression

Use *{}the syntax to represent selection expressions, for example:

<input type="text" th:value="*{user.name}" />

In the above example, *{user.name}represents the property userof an object named name.

URL expression

Use @{}the syntax to represent URL expressions, for example:

<a th:href="@{/users/{id}(id=${user.id})}">Edit</a>

In the above example, @{/users/{id}(id=${user.id})}represents a dynamic URL, where {id}represents a parameter and ${user.id}represents the value of the parameter.

conditional judgment

Use th:ifand th:unlessto make conditional judgments, for example:

<div th:if="${user.isAdmin}">
    <p>Welcome, administrator!</p>
</div>
<div th:unless="${user.isAdmin}">
    <p>Welcome, user!</p>
</div>

In the above example, th:ifit means display when the expression is true, and th:unlessit means display when the expression is false.

loop through

Use th:eachto loop through, for example:

<ul>
    <li th:each="user : ${users}" th:text="${user.name}"></li>
</ul>

In the above example, th:eachit means to ${users}traverse the collection, assign each element to userthe variable, and then display user.namethe attribute.

For more Thymeleaf syntax, please refer to the official documentation: https://www.thymeleaf.org/documentation.html

Summarize

This article introduces how to use Thymeleaf, a commonly used template engine in Spring Boot, including how to configure, how to use templates, and how to pass data. Thymeleaf is a powerful and easy-to-use template engine. It provides a simple syntax and a rich tag library, allowing us to easily create dynamic web pages.

Guess you like

Origin blog.csdn.net/2302_77835532/article/details/131577214