Getting started with Thymeleaf (based on SpringBoot)

Table of contents

1 Introduction

Thymeleaf is a popular template engine, recommended by Spring Boot. Syntax introduction, more powerful functions.

Template engines: JSP, FreeMarker, Velocity, Thymeleaf

2. Import dependencies in pom.xml

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

3. Getting started with Thymeleaf

①Usage rules: As long as the page is placed in classpath:/templates/, and the file suffix is ​​.html, Thymeleaf can automatically render

Specific principles (refer to org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties),Below is part of the code
	public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";

②Getting started:

a. Import the Thymeleaf namespace (the page will be prompted for input)

b. Use Thymeleaf syntax

c. The backend puts the data in the request field

<!DOCTYPE html>
a.import Thymeleaf Namespace (page input will be prompted)
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello Thymeleaf</title>
</head>
<body>
b.use Thymeleaf Grammar (here the page is opened directly, the display is[Hello, HTML!])
<div th:text="${aa}">Hello, HTML!</div>
</body>
</html>
c.The backend puts the data into the request field
@Controller
public class HelloController {
    @RequestMapping("/hello")
    public String hello(Model model) {
        Map<String, Object> map = new HashMap<>();
        map.put("aa", "Hello, Thymeleaf!");
        model.addAllAttributes(map);
        return "hello";
    }
}

d. Start the service, visit localhost:8080/hello, and the program runs

4.Thymeleaf grammar rules

①Syntax rules: th:xx xx represents the attribute corresponding to html

Personally understand the form of grammar rules: use the Thymeleaf attribute in the html tag to display the obtained value in the tag body

E.g:
<div th:text="${aa}">[aa Corresponding value placement]</div>

②Common attributes

Attributes Corresponding Chinese description
th:insert
th:replace
Fragment inclusion
th:each Fragment iteration
th:if
th:unless
th:switch
th:case
Conditional evaluation
th:object
th:with
Local variable definition
th:attr
th:attrprepe
th:attrappen
General attribute modification
th:value
th:href
th:src
...
Modify the default value of the specified attribute (Specific attribute modification th:value)
th:text
th:utext
Text (tag body modification)
th:text will output the content as it is; th:utext will escape the input content, and if the output value has a style, the corresponding style will be displayed.

③Expression syntax

expression describe
${...} Get variable value; conforms to OGNL expression syntax
1) Get the properties of the object and call the method
2) Get built-in objects (for detailed usage of built-in objects, see section 4.2 in the official website documentation in the appendix)
Built-in objects (some need to be obtained in the web environment): #ctx , #vars: , #locale , #request , #response , #session : , #servletContext
3) Built-in tool objects (see section 4.2 in the official website documentation in the appendix)
Built-in tool objects: #execInfo, #messages, #uris, #conversions, #dates, #calendars, #numbers, #strings, #objects, #bools, #arrays, #lists, #sets, #maps, #aggregates, # ids
*{...} 1) Consistent with the ${...} function
2) Use with th:object
example:

Name: Sebastian.


Surname: Pepper.


Nationality: Saturn.



#{...} Get international content
@{...} Define URL
Benefit: No need for splicing
example:
~{...} fragment expression

④ Literals (Literals, section 4.6 of the official document)

1.text( Text literals)
<p>
Now you are looking at a <span th:text="'working web application'">template file</span>.
</p>

2.number(Number literals)
<p>The year is <span th:text="2013">1492</span>.</p>
<p>In two years, it will be <span th:text="2013 + 2">1494</span>.</p>

3.boolean ( Boolean literals)
<div th:if="${user.isAdmin() == false}">

4.null(The null literal)
<div th:if="${variable.something} == null">

5.token

⑤Other operations (sections 4.7-4.13)

1.text stitching(Appending texts)
use + number for text concatenation
<span th:text="'The name of the user is ' + ${user.name}">

2.text replacement(Literal substitutions)
|text content|,The text content can be replaced, the following two operations are equivalent
<span th:text="|Welcome to our application, ${user.name}!|"></span> <br>
<span th:text="'Welcome to our application, ' + ${user.name} + '!'"></span><br>

3.computation(Arithmetic operations)
+ , - , * , / , %
<div th:with="isEven=(${prodStat.count} % 2 == 0)">

4.comparison operation(Comparators and Equality)
> , < , >= ,<= , == ,!=
<div th:if="${prodStat.count} &gt; 1">
<span th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')">

5.Ternary operator(Conditional expressions)
<tr th:class="${row.even}? 'even' : 'odd'">
...
</tr>

appendix

Thymeleaf official documentation

Tags: Java

Posted by vin_akleh on Mon, 30 May 2022 08:20:55 +0530