当前位置:网站首页>`Thymeleaf ` template engine comprehensive analysis
`Thymeleaf ` template engine comprehensive analysis
2022-06-24 14:18:00 【Yusheng 168】
List of articles
Thymeleaf
template engine
1. introduction
First step : Create a SpringBoot
engineering
Introduce relevant scenario initiators
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
The second step : Write the controller layer
@Controller
public class ThymeleafController {
@RequestMapping("/")
public String helloThymeleaf(Model model){
// towards request Store data in domain
model.addAttribute("data"," Welcome to use Thymeleaf template engine ");
return "hello";
}
}
The third step : Write page , towards request
Get data from shared domain
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>hello page </title>
</head>
<body>
<h3 style="color: green">Thymeleaf Use of template engine </h3>
<p th:text="${data}"> Data display area </p>
</body>
</html>
2. Use spring.thymeleaf
You can modify the default configuration in the template engine
# Change the port number to 80
server.port=80
# In the development stage , The template cache is usually turned off , Let the changes take effect immediately , The default is true Open ,
# After the project goes online , To modify back to open
spring.thymeleaf.cache=false
# Coding mode
spring.thymeleaf.encoding=UTF-8
# Type of template ( The default is html, The template is html file )
spring.thymeleaf.mode=HTML
# The prefix of the template : Classpath : classpath:/templates/
spring.thymeleaf.prefix=classpath:/templates/
# Suffix of template :
spring.thymeleaf.suffix=.html
expression
1. Standard variable expression
grammar :
${key}
effect : obtain key
For text data ,key
yes request
scoped key
, Use request.setAttribute();
or model.addAttribute();
In the page html
In the label , Use th:text="${key}"
Case study :
The first 0 Step : To write JavaBean
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Person {
private Integer id;
private String name;
private String sex;
private Integer age;
}
First step : Write controller
@RequestMapping("/expressionl")
public String expressionl(Model model){
// towards request Storing data in a shared domain
model.addAttribute("site","https://fanyi.baidu.com/");
model.addAttribute("pojo",new Person(101," The sea, "," male ",23));
// Specify jump view
return "standard";
}
The second step : Write page
<div style="margin-left: 430px">
<h3 style="color: green"> Standard variable expression </h3>
<a th:href="${site}"> Go to Baidu to translate </a><br/>
<p th:text="${pojo.id}">id</p>
<p th:text="${pojo.name}"> full name </p>
<p th:text="${pojo.sex}"> Gender </p>
<p th:text="${pojo.age}"> Age </p>
</div>
The third step : test
2. Select variable expression
grammar :
*{key}
explain : Need to match th:object
Use it together , Select variable expression , It's also called an asterisk variable expression , Use th:object
Property to bind the object , The selection expression first uses th:object
To bind the object passed from the background , And then use *
To represent the back of this object {}
Values in this object's properties
Select variable expression *{...}
Is another expression similar to a standard variable ${...}
Methods of representing variables , Select variable expression *{...}
It is solved on the selected object during execution , and ${...}
Is a variable in context model
Upper solution
Select a variable expression to use :
First step :<div th:object="${ Background incoming objects }></div>"
The second step :th:text="*{ Object properties }"
Case study :
The first 0 Step :
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Person {
private Integer id;
private String name;
private String sex;
private Integer age;
}
First step : Write controller
@RequestMapping("/expression2")
public String expression2(Model model){
model.addAttribute("pojo",new Person(102," zhanjiang "," male ",23));
return "expression2";
}
The second step : Write page
<div>
<h3 style="color: green"> Selector expressions </h3>
<div th:object="${pojo}">
<p th:text="*{id}">id</p>
<p th:text="*{name}">name</p>
<p th:text="*{sex}">sex</p>
<p th:text="*{age}">age</p>
</div>
</div>
The third step : test
3. Link expression URL
grammar :
@{ link url}
explain : Mainly used to link , Display of address , Can be used for <srcipt src="..">
<link href="..">
<a href="..">
<form action="..">
<img src="..">
etc. , Can be in URL
Get data dynamically in the path
Case study :
The first 0 Step :
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Student {
private Integer studId;
private String studName;
}
First step : Write the controller method
@Controller
@RequestMapping("/thy")
public class LinkController {
@RequestMapping("/student")
public String student(Model model){
model.addAttribute("studId",101);
return "link";
}
@RequestMapping("/queryById")
@ResponseBody
public String queryById(@RequestParam("id") Integer id){
return " according to Id Student information queried "+id;
}
@RequestMapping("/findStudent")
@ResponseBody
public Student student(Student student){
// return Student object JSON Format
return student;
}
}
The second step : Write page
<div>
<h3 style="color: green"> Link expression </h3>
<a th:href="@{
'/thy/queryById?id='+${studId}}"> according to Id Search for student information </a><br/>
<!-- Recommended Mode two :-->
<a th:href="@{/thy/findStudent(studId=${studId},studName=' The sea, ')}"> Query student information and return JSON data format </a>
</div>
Step four : test
Thymeleaf
attribute
Concept : Most attributes and html
The same as , Just add one in front th
Prefix , added th
Properties of prefixes , It is processed by the template engine
1.th:action
Define the path of the background controller , similar <form>
Labeled action
attribute , Mainly combined with url
expression , Get dynamic variables
<form id="login" th:action="@{/login}" th:method="post">...</form>
2.th:method
Set the request method
<form id="login" th:action="@{/login}" th:method="post">...</form>
3.th:href
Define hyperlinks , Mainly combined with url
expression , Get dynamic variables
<a th:href="@{query/student}"> The relative address has no parameters </a>
4.th:src
Used to import external resources , such as <script>
Labeled src
attribute ,<img>
Labeled src
attribute , Often with @{}
Expressions are used in conjunction with , stay SpringBoot
The static resources of the project are put into resources
Of static
Under the table of contents , Put it in static
The content of the path , When writing the path, you don't need to write static
script type="text/javascript" th:src="@{/js/jquery-3.4.1.js}"></script>
5.th:text
For text display , The text displayed by this attribute is in the label body , If the text box , The data will be displayed outside the text box , To display in a text box , Use th:value
<input type="text" id="realName" name="reaName" th:text="${realName}">
6.th:style
Set the style <a th:onclick="funl('+${user.id}+')" th:style="color:red"> Let me try </a>
7.th:each
[ a key ]
This property is very, very , For example, if an object collection is passed from the background, you can use attributes to traverse the output , It is associated with jstl
Medium <c:forEach>
similar , This property can loop through the collection , You can also loop through arrays and Map
A.List
aggregate
Case study :
The first 0 Step :
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Person {
private Integer id;
private String name;
private String sex;
private Integer age;
}
First step : Write controller
@Controller
@RequestMapping("/collection")
public class CollectionController {
@RequestMapping("/list")
public String list(Model model){
List<Person> list = new ArrayList<>();
list.add(new Person(101," zhanjiang "," male ",21));
list.add(new Person(102," The sea, "," male ",21));
list.add(new Person(103," nanning "," Woman ",21));
// towards request Storing data in a shared domain
model.addAttribute("list",list);
return "list";
}
}
The second step : Write page
<div>
<table>
<tr>
<th> Number </th>
<th> full name </th>
<th> Gender </th>
<th> Age </th>
</tr>
<tr th:each="person:${list}">
<td th:text="${person.id}"></td>
<td th:text="${person.name}"></td>
<td th:text="${person.sex}"></td>
<td th:text="${person.age}"></td>
</tr>
</table>
</div>
The third step : test
B. Array
Case study :
The first 0 Step :
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Person {
private Integer id;
private String name;
private String sex;
private Integer age;
}
First step : Write controller
@RequestMapping("/arr")
public String arr(Model model){
Person[] people = new Person[3];
people[0] = new Person(101," zhanjiang "," male ",21);
people[1] = new Person(102," The sea, "," male ",21);
people[2] = new Person(103," Xi'an "," Woman ",21);
// towards request Store data in domain
model.addAttribute("arr",people);
return "arr";
}
The second step : Write page
<div>
<table>
<tr>
<th> Number </th>
<th> full name </th>
<th> Gender </th>
<th> Age </th>
</tr>
<tr th:each="person:${arr}">
<td th:text="${person.id}"></td>
<td th:text="${person.name}"></td>
<td th:text="${person.sex}"></td>
<td th:text="${person.age}"></td>
</tr>
</table>
</div>
The third step : test
grammar :
th:each=person,iterStat:${collection}
Medium ${collection}
It's a collection from the background
person
: Defining variables , To receive traversal${collection}
A data in a collectioniterStat
${collection}
Circular body information
- among
person
AnditerStat
You can choose any name you like iterStat
Is the information of the circular body , The following information can be obtained through this variableindex
: Of the current iteration objectindex
( from 0 Start calculating )count
: Number of current iteration objects ( from 1 Start calculating )size
: The size of the object being iteratedcurrent
: The current iteration variableeven/odd
: Boolean value , Is the current loop even / Odd number ( from 0 Start calculating )first
: Boolean value , Whether the current loop is the firstlast
: Boolean value , Whether the current cycle is the last
Be careful : Circular body information iterStat
It can also be undefined , The iteration variable plus... Is used by default Stat
suffix , namely personStat
Array and List
Summary of set Syntax :
<div th:each=" Set loop members , The state variable of the loop :${key}">
<p th:text="${ Set loop members }" ></p>
</div>
Set loop members , The state variable of the loop : Both names are custom . “ The state variable of the loop ” This name can be undefined , The default is " Set loop members Stat"
C.Map
aggregate
Case study :
The first 0 Step :
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Person {
private Integer id;
private String name;
private String sex;
private Integer age;
}
First step : Write controller
@RequestMapping("/map")
public String map(Model model){
Map<String,Object> map = new HashMap<>();
map.put("101",new Person(101," The sea, "," male ",21));
map.put("102",new Person(102," zhanjiang "," male ",22));
map.put("103",new Person(103," Xi'an "," Woman ",23));
map.put("104",new Person(104," nanning "," Woman ",21));
// towards request Store data in domain
model.addAttribute("map",map);
return "map";
}
The second step : Write page
<div>
<table>
<tr>
<th> Number </th>
<th> full name </th>
<th> Gender </th>
<th> Age </th>
</tr>
<tr th:each="perMap:${map}">
<td th:text="${perMap.key}"></td>
<td th:text="${perMap.value.name}"></td>
<td th:text="${perMap.value.sex}"></td>
<td th:text="${perMap.value.age}"></td>
</tr>
</table>
</div>
The third step : test
Map
Summary of set Syntax
<div th:each=" Set loop members , The state variable of the loop :${key}">
<p th:text="${ Set loop members .key}" ></p>
<p th:text="${ Set loop members .value}" ></p>
</div>
Set loop members , The state variable of the loop : Both names are custom . “ The state variable of the loop ” This name can be undefined , The default is " Set loop members Stat"
key:map In the collection key
value:map aggregate key Corresponding value value
8. conditional if
-unless
grammar :
th:if="boolean Conditions "
Condition is
true
Display body content
th:unless
yesth:if
An opposite operation of
Note that : When th:if=${..}
When grammar holds , Will display the contents in the label body 【 Namely if by true when , Show 】
Note that : When th:unless=${..}
When grammar doesn't hold , Will display the contents in the label body 【 Namely unless by false when , Show 】
Minutiae :
- stay
th:if="${""}"
In the sentence 【 An empty string 】 Representative istrue
- stay
th:if="${null}"
In the sentence 【null
Representative is false】
Case study :
First step : Write controller
@RequestMapping("/MyIf")
public String myIf(Model model){
// Store data in a shared domain
model.addAttribute("sex"," Gender unknown ");
// Note that : stay `th:if` Statement empty string , Representative is true
// Note that : stay `th:unless` Statement empty string , Representative is true,true Do not show ,false Only show
model.addAttribute("name","");
// Note that : stay `th:if` In the sentence `null`, Representative is false
// Note that : stay `th:unless` In the sentence `null`, Representative is false,false Is displayed
model.addAttribute("old",null);
return "MyIf";
}
The second step : Write page
<div>
<h3 style="color: green">IF Judgment statement </h3>
<!-- The following two ways are both correct -->
<p th:if="${sex==' Gender unknown '}"> Gender unknown </p>
<p th:if="${sex}==' Gender unknown '"> Show gender </p>
<!-- Empty string in `th:if` Representative is true,true stay unless Not shown in -->
<p th:if="${name}"> stay th:if The empty string represents true</p>
<!-- null stay `th:if` Representative is false,false stay `th:unless` Is displayed -->
<p th:unless="${old}"> stay `th:if` in null Representative is false,false The label is not displayed , stay nuless In, it shows </p>
</div>
The third step : test
9.th:switch
th:switch
and java
Medium swith
Same
grammar :
<div th:switch=" The value to compare ">
<p th:case=" value 1">
result 1
</p>
<p th:case=" value 2">
result 2
</p>
<p th:case="*">
Default results
</p>
The above case Only one statement executes
</div>
Note that :th:case="*"
Represents the default value
Case study :
First step : Write controller
@RequestMapping("/switch")
public String switchCase(Model model){
// request Storing data in a shared domain
// stay switch Is displayed only when it is matched in , If they do not match, you can use `th:switch="*"` Set default
model.addAttribute("sex"," male ");
return "switch";
}
The second step : Write page
<div>
<h3 style="color: green">switch Judgment statement </h3>
<div th:switch="${sex}">
<p th:case=" male "> Gender male </p>
<p th:case=" Woman "> Gender female </p>
<!-- `th:case="*"` The expression is default -->
<p th:case="*"> Gender unknown </p>
</div>
</div>
The third step : test
10.th:inline
th:inline
There are three value types {text javascript and none}
inline text
It can make Thymeleaf
The expression does not depend on html
label , You can get dynamic data directly by using inline expressions , It is required to add... To the parent label th:inline="text" attribute
inline javascript
Can be in js
in , Get the data in the template
Case study :
First step : Write controller
@RequestMapping("/inline")
public String inline(Model model){
// request Storing data in a shared domain
model.addAttribute("name"," The sea, ");
model.addAttribute("age","20");
return "inline";
}
The second step : Write page
<style> * {
width: 500px; margin: 0 auto; } </style>
<script type="text/javascript" th:inline="javascript"> var name = [[${
name}]]; function fun() {
alert(" My name is :"+name+"\t My age is :"+[[${
age}]]); } </script>
</head>
<body>
<div>
<h3> Inline expressions </h3>
<p> My name is :[[${name}]], Age is :[[${age}]]</p>
<input type="button" value=" Let me try " onclick="fun()">
</div>
The third step : test
11. Literal
The literal amount of the text
single quote '..'
The enclosed string is text literal
Case study :
<p th:text="' The city is '+${city}+' The user login '+${isLogin}"></p>
Number literal quantity
<p th:if="${age>10}">age>10</p>
<p th:if="20>5">20 Greater than 5</p>
boolean
Literal
<p th:if="${isLogin==true}"> The user login </p>
12. String connection
Mode one : Use ''
Case study :
<p th:text="' The city is '+${city}+' The user login '+${isLogin}"></p>
Mode two : Use ||
【 It is suggested to use mode 2 】
Case study :
<p th:text="| The city is ${city}, I am a ${name}|">
Display the data
</p>
Case study :
First step : Write controller
@RequestMapping("/strJoin")
public String strJoin(Model model){
// towards request Shared data in domain
model.addAttribute("city"," The sea, ");
model.addAttribute("name"," Tomorrow, ");
model.addAttribute("age",23);
// View jump
return "strJoin";
}
The second step : Write page
<div>
<h3 style="color: green"> String splicing method 1 : Use `'..'`</h3>
<p th:text="' I am a '+${name}+', My city '+${city}+' My age is :'+${age}"> Display personal information </p>
<br/>
<br/>
<h3 style="color: green"> String splicing mode 2 : Use `||`</h3>
<p th:text="| I am a ${name}, My city ${city}, My age is : ${age}|"> Display personal information </p>
</div>
The third step : test
13. Operator
Arithmetic operations :
+
-
*
/
%
The relationship is more :
>
<
>=
<=
(gt lt ge le)
Equal to the judge :
==
!=
(eq ne)Ternary operator :
expression ? true Result : false Result
Ternary operators can be nested
Case study :
First step : Write controller
@RequestMapping("/operation")
public String operation(Model model){
// Store data in a shared domain `request`
model.addAttribute("name"," The sea, ");
model.addAttribute("age",21);
// View jump
return "operation";
}
The second step : Write page
<div>
<h3 style="color:green;"> Operator </h3>
<p th:if="${name==' The sea, '}"> Expression for true, Is displayed </p>
<p th:if="${age}>20 ? ' Older than 20' : ' Be no older than 20'"> Judge whether the age is older than 20</p>
</div>
The third step : test
Thymeleaf
The basic object
1. Common built-in objects
The template engine provides a set of objects , These built-in objects can be used directly in the template , These objects are made up of #
No. begins to refer to , We often use built-in objects
request
object
#request
Prototype :HttpServetRequest
object
session
object
#session
Prototype :HttpSesssion
object
session
Prototype :HttpSession
object
Session
Expressed as Map
Object's , yes #session
A simple representation of , Used to obtain session
Specified in the key
Value ,#session
Is used to call related methods
Case study :
First step : controller
@RequestMapping("/baseObject")
public String baseObject(Model model, HttpSession session){
// towards request Store data in domain
model.addAttribute("name"," zhanjiang ");
// towards session Store data in domain
session.setAttribute("age",23);
return "baseObject";
}
The second step : Write page
<div>
<h3 style="color: green"> Use of basic built-in objects </h3>
<p th:text="${#request.getAttribute('name')}"></p>
<p th:text="${#session.getAttribute('age')}"></p>
<p th:text="${session.age}"></p>
<h3 style="color: green">`#request` The use of built-in objects </h3>
getServerPort: <span th:text="${#request.getServerPort()}"></span><br/>
getRequestURI<span th:text="${#request.getRequestURI()}"></span><br/>
getRequestURL<span th:text="${#request.getRequestURL()}"></span><br/>
<h3 style="color: green">`#session` The use of built-in objects </h3>
getId<span th:text="${#session.getId()}"></span>
</div>
The third step : test
2. Based on built-in objects #ctx
grammar :
#ctx: context object
You can get other built-in objects
Note that :#vars
and #root
Is the same object , and #ctx
It does the same thing , It is recommended to use #ctx
/* * ====================================================================== * See javadoc API for class org.thymeleaf.context.IContext * ====================================================================== */
${
#ctx.locale}
${
#ctx.variableNames}
/* * ====================================================================== * See javadoc API for class org.thymeleaf.context.IWebContext * ====================================================================== */
${
#ctx.request}
${
#ctx.response}
${
#ctx.session}
${
#ctx.servletContext}
#locale # place : direct access to the : Go straight into
java.util.Locale
associated with current request. Related to the current request 【 Get information about the current location 】param : for retrieving request parameters. : Used to retrieve request parameters
${param.foo}
is a It's aString[]
with the values of the Valuefoo
request parameter, so Request parameters , therefore${param.foo[0]}
will normally be used for getting the first value. Will usually be used to get the first value
/* * ============================================================================ * See javadoc API for class org.thymeleaf.context.WebRequestParamsVariablesMap * ============================================================================ */
${
param.foo} // Retrieves a String[] with the values of request parameter 'foo'
${
param.size()}
${
param.isEmpty()}
${
param.containsKey('foo')}
...
- session meeting : for retrieving session attributes. : Used to retrieve session properties
/* * ====================================================================== * See javadoc API for class org.thymeleaf.context.WebSessionVariablesMap * ====================================================================== */
${
session.foo} // Retrieves the session atttribute 'foo'
${
session.size()}
${
session.isEmpty()}
${
session.containsKey('foo')}
...
- application apply : for retrieving application/servlet context attributes. Used to retrieve application/servlet Context properties
/* * ============================================================================= * See javadoc API for class org.thymeleaf.context.WebServletContextVariablesMap * ============================================================================= */
${
application.foo} // Retrieves the ServletContext atttribute 'foo'
${
application.size()}
${
application.isEmpty()}
${
application.containsKey('foo')}
...
Note there is no need to specify a namespace for accessing request attributes (as opposed to request parameters) because all request attributes are automatically added to the context as variables in the context root:
Be careful , There is no need to specify a namespace for the access request attribute ( Contrary to the request parameters ) , Because all request attributes are automatically added to the context as variables in the context root :
${
myRequestAttribute}
stay Web Environment , You can also directly access the following objects ( Be careful , These are objects , Not a map / The name space ) :
- #request # request : direct access to the : Go straight into
javax.servlet.http.HttpServletRequest
object associated with the current request. Associated with the current request
${
#request.getAttribute('foo')}
${
#request.getParameter('foo')}
${
#request.getContextPath()}
${
#request.getRequestName()}
...
- #session # meeting : direct access to the : Go straight into
javax.servlet.http.HttpSession
object associated with the current request. Associated with the current request
${
#session.getAttribute('foo')}
${
#session.id}
${
#session.lastAccessedTime}
...
- #servletContext # servletContext : direct access to the : Go straight into
javax.servlet.ServletContext
object associated with the current request. Associated with the current request
${
#servletContext.getAttribute('foo')}
${
#servletContext.contextPath}
...
3. Built in tool class
Built in tool types :Thymeleaf
Some of their own classes , Provide right string
date
, Some processing methods of collection
#dates
: Tool class for processing dates
#numbers
: Dealing with digital tools
#lists
: Handlelist
Collection tool class
null
value : Handle , Add after object?
, Indicates whether the current object isnull
, Ifnull
Then the following values will not be takenfor example :
zoo?.dog?.name
: Said ifzoo
bynull
, Do not carry outdog
The value of , Ifdog
bynull
, Do not carry outname
The value of , It can prevent error reporting
Case study :
The first 0 Step : Write entity class
@Data
@ToString
public class Cat {
private String name;
}
@Data
@ToString
public class Dog {
private String name;
}
@Data
@ToString
public class Zoo {
private Dog dog;
private Cat cat;
}
First step : Write the controller layer
@RequestMapping("/utilObject")
public String utilObject(Model model){
// towards request Domain stores data
model.addAttribute("myDate",new Date());
// towards request Fields store numbers
model.addAttribute("num",168.868);
// towards request Domain store string
model.addAttribute("str","haikang168");
// towards request Domain storage list aggregate
List<String> list = Arrays.asList("a","b","c","d","e");
model.addAttribute("list",list);
// towards request Store objects in the domain
Dog dog = new Dog();
dog.setName(" Dog ");
Cat cat = new Cat();
cat.setName(" people of little importance ");
Zoo zoo = new Zoo();
zoo.setCat(cat);
zoo.setDog(dog);
model.addAttribute("zoo",zoo);
return "utilObject";
}
The second step : Write page
<div>
<h3 style="color: green"> Date tool class </h3>
<!-- Note that : Pass in the property name directly in the method , Out of commission `${ Property name }`-->
<p th:text="${#dates.format(myDate)}"></p>
<p th:text="${#dates.format(myDate,'yyyy-MM-dd HH:mm:ss')}"></p>
<p th:text="${#dates.year(myDate)}"></p>
<p th:text="${#dates.month(myDate)}"></p>
<!-- createNow Create current time -->
<p th:text="${#dates.createNow()}"></p>
<h3 style="color: red"> Digital tools </h3>
<!-- Currency Is to format the currency -->
<p th:text="${#numbers.formatCurrency(num)}"></p>
<!-- formatDecimal Is to format numbers , The length is 5, And save 2 Decimal place -->
<p th:text="${#numbers.formatDecimal(num,5,2)}"></p>
<h3 style="color: mediumspringgreen"> String utility class </h3>
<p th:text="${#strings.indexOf(str,'h')}"></p>
<p th:text="${#strings.isEmpty(str)}"></p>
<p th:text="${#strings.length(str)}"></p>
<!-- lists Tool class -->
<h3 style="color: skyblue">list Collection tool class </h3>
<p th:text="${#lists.size(list)}"></p>
<p th:text="${#lists.toList(list)}"></p>
<p th:text="${#lists.sort(list)}"></p>
<!-- null Value processing uses `?`-->
<h3 style="color: blanchedalmond">null Value handling </h3>
<p th:text="${zoo?.cat?.name}"></p>
<p th:text="${zoo?.dog?.name}"></p>
</div>
The third step : test
4. Template content reuse
Custom templates are reusable behaviors , You can put some content , Use repeatedly
First step : Define templates
grammar :
th:fragment="top"
: Represents the definition template , The custom name istop
for example :
<div th:fragment="top">
<p> Dahaikang </p>
<p> Welcome to our hotel !</p>
</div>
Define template method 2 : Don't use th:fragment="top"
, It means that the entire page can be referenced
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<p>all page </p>
<p> Don't use `th:fragment` Syntax definition template , Indicates that the entire page can be used as a template </p>
</div>
</body>
</html>
The second step : How to reference a template 【 There are two kinds of 】
<body>
...
<div th:insert="~{footer :: copy}"></div>
</body>
The top and bottom are identical
<body>
...
<div th:insert="footer :: copy"></div>
</body>
Express ~{footer :: copy}
Function and footer :: copy
It works the same
The third step : We can use copy th:insert th:replace th:include
Three ways to introduce public pages , Pay attention to thymeleaf3.0
It is no longer recommended to use th:include
th:insert
th:replace
th:include
Differences among the three
th:insert
It's the simplest , It inserts the public fragment into the specified fragmentth:replace
Actually replace the specified fragment withth:include
Similar to , But not an insert , Instead, just insert the content of this clip
Public segment :
<footer th:fragment="copy">
© 2011 The Good Thymes Virtual Grocery
</footer>
Three ways :
<body>
...
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>
</body>
The effect of the action :
<body>
...
<div>
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
</div>
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
<div>
© 2011 The Good Thymes Virtual Grocery
</div>
</body>
Case study :
First step : Write a public page fragment.html
page
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title> Custom template </title>
</head>
<body>
<div th:fragment="top">
<p> Dahaikang </p>
<p> Welcome to our hotel !</p>
</div>
</body>
</html>
all.html
page
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<p>all page </p>
<p> Don't use `th:fragment` Syntax definition template , Indicates that the entire page can be used as a template </p>
</div>
</body>
</html>
Different levels of pages common.html
Note that :commont
The folder is at the same level as the reference page
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title> Public pages </title>
</head>
<body>
<div th:fragment="body">
<p> Said is : How to reference public pages in different directories </p>
<p>th:insert=" Destination address 【 Generally, relative paths are used 】 :: Fragment name "</p>
</div>
</body>
</html>
The second step : Define reference pages and use syntax to reference public pages
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title> Custom template reference </title>
<style> * {
width: 500px; margin: 0 auto; } </style>
</head>
<body>
<h3 style="color: mediumspringgreen"> How to introduce fragments </h3>
<!-- Mode one : Use insert and ~{fragment :: top} Way to introduce -->
<div th:insert="~{fragment :: top}"></div>
<!-- Mode two : Use include and `fragment :: top`-->
<div th:include="fragment :: top"></div>
<!-- Mode three : Use -->
<div th:replace="fragment :: top"></div>
<br/>
<br/>
<br/>
<h3 style="color: skyblue"> Introduce the whole page mode </h3>
<!-- Mode one : Presentation reference `all` page ,`html` It refers to the whole page -->
<div th:insert="all :: html"></div>
<!-- Mode two : Don't write `html`-->
<div th:insert="~{all}"></div>
<br/>
<br/>
<br/>
<h3 style="color: green"> Reference the public pages under different layer directories </h3>
<div th:replace="common/common :: body"></div>
</body>
</html>
边栏推荐
- 4个不可不知的“安全左移”的理由
- tongweb使用之端口冲突处理办法
- 数字臧品系统开发 NFT数字臧品系统异常处理源码分享
- ASCII code table extracted from tanhaoqiang's C program design (comparison table of common characters and ASCII codes)
- 在CVS中恢复到早期版本
- Generate binary tree according to preorder & inorder traversal [partition / generation / splicing of left subtree | root | right subtree]
- 文本对比学习综述
- 09_一种比较高效的记忆方法
- Digital business cloud: strengthen supplier management and promote efficient collaboration between air transport enterprises and suppliers
- leetcode:1504. 统计全 1 子矩形的个数
猜你喜欢
AntD checkbox,限制选中数量
GO语言并发模型-MPG模型
根据前序&中序遍历生成二叉树[左子树|根|右子树的划分/生成/拼接问题]
港股上市公司公告 API 数据接口
如何解决 Iterative 半监督训练 在 ASR 训练中难以落地的问题丨RTC Dev Meetup
初识云原生安全:云时代的最佳保障
【深度学习】NCHW、NHWC和CHWN格式数据的存储形式
Linux 安装 CenOS7 MySQL - 8.0.26
[deep learning] storage form of nchw, nhwc and chwn format data
Rasa 3.x 学习系列-非常荣幸成为 Rasa contributors 源码贡献者,和全世界的Rasa源码贡献者共建共享Rasa社区!
随机推荐
六月集训(第24天) —— 线段树
Kotlin coordination channel
Jerry's test mic energy automatic recording automatic playback reference [article]
PgSQL queries the largest or smallest data of a field in a group
【从零开始学zabbix】一丶Zabbix的介绍与部署Zabbix
conda和pip命令
JS remove string spaces
R语言plotly可视化:使用plotly可视化数据划分后的训练集和测试集、使用不同的形状标签表征、训练集、测试集、以及数据集的分类标签(Display training and test split
P2pdb white paper
Three efficient programming skills of go language
21set classic case
MySQL日志管理、备份与恢复
Halcon 绘制区域 到图片中
Keras深度学习实战(11)——可视化神经网络中间层输出
数商云:加强供应商管理,助推航空运输企业与供应商高效协同
Idea connection MySQL custom generated entity class code
Harmony os. (2)
Jerry added an input capture channel [chapter]
Jerrys timer0 uses the default pa13 to detect the pulse width [chapter]
Jericho turns on shouting in all modes to increase mic automatic mute [chapter]