SpringBoot learning---thymeleaf template engine

1. What is thymeleaf

1. Template engine

Baidu Encyclopedia:

The template engine (here refers specifically to the template engine for Web development) is generated to separate the user interface from the business data (content), it can generate documents in a specific format, and the template engine used for the website will generate a standard HTML document.

insert image description here

2.thymeleaf template engine

insert image description here

3. Learning materials

(1) Thymeleaf official website: https://www.thymeleaf.org/Official
development documentation (English version)
insert image description here
insert image description here
Official development documentation (Chinese version), translated by the author Liu Minggang.
insert image description here
insert image description here
Download link:
Tencent Weiyun Download link: https://share.weiyun.com/7nezzZwD Password: xmahjk
Baidu network disk download link: https://pan.baidu.com/s/1BBJJ5_N8St6BoPem6A_qJg
Extraction code: y4hm

(2) Thymeleaf's homepage on Github
insert image description here

(3) Spring official documentation: You can find the version corresponding to our thymeleaf
insert image description here

Two.thymeleaf basic grammar

1. Project introduction

Import dependencies in pom.xml

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

Related jar packages:
insert image description here

2. Source code analysis

Take a look at the source code of thymeleaf's auto-configuration class ThymeleafProperties:

ctrl+shift+T输入ThymeleafProperties
insert image description here
insert image description here
从源代码中的前缀和后缀我们可猜想,使用thymeleaf是不是只需把我们的html页面放在类路径下的templates下,thymeleaf就可以帮我们自动渲染了?

为了证实我们的猜想,新建一个SpringBoot项目,导入Web依赖,删除不需要部分,项目结构如下:
insert image description here
导入thymeleaf的依赖:
insert image description here
在templates文件下新建一个test.html文件:
insert image description here
新建一个controller文件,并在该文件下新建一个TestController类:
insert image description here
运行Web程序:
insert image description here
因为thymeleaf最大的作用就是数据和界面分离,这里并没有涉及到数据,通过上面的操作还无法说明,我们通过编写相应代码将数据传递给前端再交给thymeleaf对界面进行渲染。

在test.html中导入thymeleaf模板引擎命名空间:

xmlns:th="http://www.thymeleaf.org"

insert image description here
重新编写一下test.html代码:
insert image description here
其实这个和JSP很像,JSP是这样写的:
insert image description here
后端操作基本上是和以前一样,在TestController类中:
insert image description here
编写完之后,test.html中的msg就不再报错:
insert image description here
再次运行项目:
insert image description here
前面分析中说到,将XX.html文件放在templates文件下就会自动渲染,为了进一步证明这一点,我们先将test.html放到static中(static文件中通过静态资源是可以访问的),看看数据是不是还会显示。
当我们把test.html放到static中的时候,msg就变红了,说明我们分析是正确的:
insert image description here
insert image description here

3.基础语法学习

(1) th:text/utext,th:value,th:each

Commonly used data bindings:

  • bind a string
 th:text="${msg}" 和 th:utext="${msgUtext}"
  • .Bind a pojo object
 th:value="${user.name}"
  • bind a list
 <tr th:each="e:${userList}">
 	<td th:text="${e.id}"></td>
 	<td th:text="${e.name}"></td>
    <td th:text="${e.age}"></td>
          
 </tr>
  • bind a map
 <tr th:each="e,eState:${userMap}">
        <td th:text="下标:${eState.index+1}"></td>
        <td th:text="${e.name}"></td>
        <td th:text="${e.age}"></td>
 </tr>

Create a new pojo file and create the User class under this file:
insert image description here
Note, don't forget to import the lombok dependency.
insert image description here
TestController class:
insert image description here

test.html (this file is put back into the templates file):

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
后端传递的数据为:
<p th:text="${msg}"></p>
<p th:utext="${msgUtext}"></p>

用户信息:
用户ID:<input type="text" th:value="${user.getUserId()}">
用户姓名:<input type="text" th:value="${user.getName()}">
用户年龄:<input type="text" th:value="${user.getAge()}">


</br>获取一组用户数据:
<table border="1px" th:width="200px">
    <thead>
    <tr>
        <th>用户ID</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>序号</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="e:${userList}">
        <td th:text="${e.getUserId()}"></td>
        <td th:text="${e.getName()}"></td>
        <td th:text="${e.getAge()}"></td>
        <td th:text="${e.getUserId()-1}"></td>
    </tr>
    </tbody>
    <tbody>
    <tr th:each="e,eState:${userMap}">
        <td th:text="${e.getValue().getUserId()}"></td>
        <td th:text="${e.getValue().getName()}"></td>
        <td th:text="${e.getValue().getAge()}"></td>
        <td th:text="${eState.index}"></td>
    </tr>
    </tbody>
</table>
</body>
</html>

running result:
insert image description here

Question 1: What is the difference between th:text and th:utext?
The data passed to the front end is as follows:
insert image description here
Display situation:
insert image description here
从中我们可以得出:text不会解析html,utext会解析html

Question 2:<tr th:each="e:${userList}"><tr th:each="e,eState:${userMap}">
What is the difference between and
insert image description here

(2) th:if

Basic relationship:
insert image description here

Query the names of users whose age is greater than 20:

<p th:text="${user.name}" th:if="${user.age gt 20}"></p>

For other properties, check the official website API documentation:
insert image description here

(3) Expressions (variables, links, messages, code blocks, selection variables)

insert image description here

  • ${…}variable expression

Variable expressions can get the properties and methods of objects, including some built-in objects and built-in methods.

In the previous examples, we are all methods of obtaining objects and returning the corresponding value:
insert image description here
in fact, we can directly obtain the value directly through the attribute: of
insert image description here
course, for some built-in objects, we can also obtain:
built-in objects:
insert image description here
such as the current language situation:
insert image description here
running effect:
insert image description here
of course, for some We can also get built-in methods:
(The following figure shows some commonly used built-in methods)
insert image description here
For example:
insert image description here

running result:
insert image description here

  • @{…} link expression

Whether it is a static resource reference, a form request, or any link, @{…} can be used. In this way, the project path can be dynamically obtained, and even if the project name changes, it can still be accessed normally.

  • No parameter: @{/xxx}
  • There are parameters: @{/xxx(k1=v1,k2=v2)} Corresponding url structure: xxx?k1=v1&k2=v2
  • Introduce local resources: @{/project-local resource path}
  • Introduce external resources: @{/webjars/resource path in jar package}

E.g:
insert image description here

  • #{…}Message expression

Message expressions are generally used in internationalization scenarios. Internationalization allows us to get local text information (.properties) from an external file, index Value with Key, and provide a set of parameters (optional).

(In the case of internationalization configuration) the value obtained by user.name here will display different content according to the language selection!

 <th th:text="#{user.name}">...</th>  
  • ~{…} code expression

There are two ways to declare:
Recommended: Support:~{templatename::fragmentname}
~{templatename::#id}


Explanation of related parameters:

templatename: Template name, Thymeleaf will parse the full path according to the template name: /resources/templates/templatename.html, pay attention to the path of the file.
fragmentname: Fragment name, Thymeleaf defines the code block through the th:fragment declaration, namely: th:fragment=“fragmentname”
id: HTML id selector, which should be preceded by # when used, class selector is not supported.


Code block expressions need to be used together with the th attribute (th:insert, th:replace, th:include):
th:insert: insert the entire code block fragment into the HTML tag that uses th:insert
th:replace: add the code The entire block fragment replaces the HTML tag using th:replace
th:include: Insert the content contained in the code block fragment into the HTML tag using th:include


Code example:
create a footer.html:
insert image description here

test.html:
insert image description here

running result:
insert image description here

  • *{…} select variable selector

Selection expressions are much like variable expressions, but they are executed with a preselected object instead of the context variable container (map)

Preselected object: user(${user})

Example:
insert image description here

Running effect:
insert image description here
Related learning links:
thymeleaf use basic tutorial
07. The most complete and detailed explanation of Thymeleaf use and grammar (fine)

Guess you like

Origin blog.csdn.net/weixin_42753193/article/details/123527037