PS: If our passion only lasts for three minutes, we cannot complete the test of faith. When confusion arises, the first thing we often do is run away. No skill can be mastered in a short time; as long as we persist long enough, time will give you the answer.
The previous article here briefly introduced the dependencies, basic properties, and usage of Thymeleaf templates. Below, we will introduce the common syntax in Thymeleaf from the following aspects:
- Expressions
- String Concatenation
- Conditional Comparison
- Switch Multiple Branches
- Loops
- Other Operators
- Inline
- Testing Effects
The specific values of some parameters or variables mentioned below are as follows:
// Test value passing
model.addAttribute("name", "jzman");
model.addAttribute("gzh", "<b>Gongxingzhi</b>");
model.addAttribute("user", new User("manu"));
model.addAttribute("id", "123456");
model.addAttribute("flag", false);
model.addAttribute("value", 10);
// Loop statement test
model.addAttribute("list", mUserList);
// span tag's id, CSS inline test
model.addAttribute("idName", "css");
// Color value to be used in CSS styles, CSS inline test
model.addAttribute("color", "#FF0000");
Expressions#
Common expressions in Thymeleaf mainly include the following types:
- Message expressions: Use
#{}
to get the corresponding value from the property file; - Variable expressions: Use
${}
to get variable values, which are generally passed in by the backend; - Selection variable expressions: Use
*{}
in conjunction with theth:object
attribute to get the property value of the object specified byth:object
; - Link URL expressions: Use
@{}
to indicate the link address, which allows for easy parameter passing in the link address.
The usage of the above expressions is shown below:
<ul th:object="${user}">
<!--Message expression-->
<li>Message expression: <span th:text="#{home.title}">Hello World!</span></li>
<!--Variable expression-->
<li>Variable expression: <span th:text="${name}">Hello World!</span></li>
<!--Selection variable expression-->
<li>Selection variable expression: <span th:text="*{username}">Hello World!</span></li>
<li>Selection variable expression: <span th:text="${user.username}">Hello World!</span></li>
<!--Link expression-->
<li>Link expression: <a href="default.html" th:href="@{default.html}">Default Page.</a></li>
<li>Link expression: <a href="default.html" th:href="@{http://localhost:8080/{path}/i18n}">I18n Page.</a></li>
<li>Link expression: <a href="default.html" th:href="@{http://localhost:8080/message(id=${id})}">Message.</a></li>
</ul>
The th
attributes in the above code are properties defined by Thymeleaf corresponding to HTML attributes. In the message expression example, the value of home.title
defined in the home.properties
file under resources
is retrieved.
In the variable expression example, the value of the variable named name
passed in by the backend is retrieved.
In the selection variable expression example, the value of username
of the object user
specified by the th:object
attribute is retrieved. When the th:object
attribute is not set, there is no difference between ${}
and *{}
; both can be used interchangeably, and *{}
can also access a property value of an object through object.property
.
In the link expression example, the link address is specified for the <a>
tag, and parameters required for the link can also be easily specified.
Let's see how the backend passes the variable name
and the object user
to the page, as shown in the code below:
String Concatenation#
String concatenation is generally done using +
to concatenate strings, and you can also use double vertical bars to wrap string content for concatenation. The usage is as follows:
<!--String concatenation-->
<!--1. Using + sign-->
<li><span>Using + sign: </span><span th:text="'My name is '+${name}+'!'">Default</span></li>
<!--2. Using | sign-->
<li><span>Using | sign: </span><span th:text="|My name is ${name}!|"></span></li>
The test results are as follows:
1. Using + sign: My name is jzman!
2. Using | sign: My name is jzman!
Conditional Comparison#
The conditional statements in Thymeleaf are th:if
and th:unless
. th:if
indicates execution when the condition is met, while th:unless
indicates execution when the condition is not met. Additionally, here are the common comparison operators in Thymeleaf:
- gt(>) : greater than
- lt(<) : less than
- ge(>=) : greater than or equal to
- le(<=) : less than or equal to
- not(!) : not
- eq(==) : equal
- neq/ne(!=) : not equal
In the above comparison operators, the corresponding strings are aliases for each comparison operator. For example, the greater-than sign can be represented by gt
. This is because Thymeleaf templates can be used in XML documents, where attribute values cannot use <
and >
tags. Of course, you can choose which method to use for project development. The usage is as follows:
<!--Conditional comparison--value=10-->
<li th:if="${value} gt 9"><span>gt(>) </span><span th:text="|${value}|+'>9'">Default</span></li>
<li th:if="${user} ne null"><span>ne(!=) </span><span th:text="'User object is not null!'">Default</span></li>
<!--if/unless-->
<li th:if="${value} gt 9"><span>if </span><span th:text="|${value}|+'>9成立时才执行'">Default</span></li>
<li th:unless="${value} gt 11"><span>unless </span><span th:text="|${value}|+'>11不成立时才执行'">Default</span></li>
The test results are as follows:
gt(>) 10>9
ne(!=) User object is not null!
if 10>9成立时才执行
unless 10>11不成立时才执行
Switch Multiple Branches#
The switch...case
statement is also a conditional statement, where th:case="*"
indicates the default selection. The usage is as follows:
<li th:switch="${name}">
<p th:case="jzman">He name is jzman.</p>
<p th:case="manu">He name is manu.</p>
<!--default-->
<p th:case="*">others</p>
</li>
The test results are as follows:
This is jzman
Loops#
Using for
loops in template code is as follows:
<li><span>No index</span>
<table>
<tr th:each="user:${list}">
<td th:text="${user.userId}"></td>
<td th:text="${user.username}"></td>
</tr>
</table>
</li>
<li><span>With index</span>
<table>
<tr th:each="user,start:${list}">
<td th:text="${start.index}"></td>
<td th:text="${user.userId}"></td>
<td th:text="${user.username}"></td>
</tr>
</table>
</li>
In the above code, start
can be used to obtain some information during the loop as follows:
- index: The index of the current iteration object, starting from 0;
- count: The index of the current iteration object, starting from 1;
- size: The size of the iterated object;
- current: The current iteration variable;
- even/odd: Boolean value indicating whether the current loop is even or odd, starting from 0;
- first: Boolean value indicating whether the current loop is the first one;
- last: Boolean value indicating whether the current loop is the last one.
The test results are as follows:
No index
1 jzman
2 Gongxingzhi
3 Tom
With index
0 1 jzman
1 2 Gongxingzhi
2 3 Tom
Other Operators#
The ?:
operator first checks if the preceding expression is null. If it is null, it uses the value of the following expression; otherwise, it uses the value of the preceding expression. The usage is as follows:
<!--?: operator: first checks if the preceding expression is null, if null, uses the value of the following expression; otherwise, uses the value of the preceding expression-->
<li><span>?: operator:</span><span th:text="${name} ?: 'default'">Default</span></li>
<!--Ternary operator can also be represented-->
<li><span>Ternary operator:</span><span th:text="${name} ne null ? ${name}:'default'">Default</span></li>
The test results are as follows:
?: operator: jzman
Ternary operator: jzman
The _
operator indicates no operation. For example, the variable test
is null, so when executing the _
operator, no operation is performed. The value in the <span>
tag is Default
:
<!--_ operator: indicates no operation-->
<li><span>_ operator:</span><span th:text="${test} ?: _">Default</span></li>
The test results are as follows:
_ operator: Default
Inline#
Thymeleaf supports expression inline, JavaScript inline, CSS inline, and text inline. Below are the three most commonly used inline methods:
- Expression inline
- JavaScript inline
- CSS inline
Expression Inline#
Expressions between [[..]]
and [(...)]
in Thymeleaf templates are called inline expressions, which are equivalent to using th:text
and th:utext
in HTML tags to set the corresponding element's text value. The usage is as follows:
<!--Expression inline-->
<!--The value of the corresponding expression is processed as text and will not process HTML tag effects-->
<li><span>Expression inline:</span> Official account name is [[${gzh}]]</li>
<!--The value of the corresponding expression is processed without text processing and will process HTML tag effects-->
<li><span>Expression inline:</span> Official account name is [(${gzh})]</li>
The biggest difference between the two is whether the text is processed. [[..]]
will not process the given text and will output it as is, while [(...)]
will render the formatted text after output. The test results are as follows:
Expression inline: Official account name is <b>Gongxingzhi</b>
Expression inline: Official account name is Gongxingzhi
In the second line, the content in the <b>
tag Gongxingzhi
is bolded, as seen in the effect image at the end.
JavaScript Inline#
JavaScript inline allows you to directly use [[${...}]]
in js code to get the value of the expression inside. When using, you need to enable JavaScript inline support by using th:inline="javascript"
in the <script>
module. The usage is as follows:
<script th:inline="javascript">
function gzhName() {
// Output unescaped characters
// let gzh = [(${gzh})];
// js gets the value of the name passed in by the backend as gzh
let gzh = [[${gzh}]];
console.log("gzhName:" + gzh);
let span = document.getElementsByClassName("jsInline");
span[0].innerHTML = gzh.toString();
}
</script>
<!--...-->
<!--JavaScript inline-->
<li><span>JavaScript inline:</span><button onclick="gzhName()">Get variable value from js</button><span class="jsInline"></span></li>
After running the program, clicking the button
will get the value of the variable gzh
. Let's look at the natural template of JavaScript, where the expression is wrapped in comments. During dynamic execution, the comments before and after the expression will be ignored, only outputting the value of the expression. If it is a static page, the value of the expression will be ignored. The usage is as follows:
// JavaScript natural template
let name = /*[[${name}]]*/ "Test";
console.log("name:" + name);
Additionally, if you need an unescaped string, you can use [(${...})]
to get it.
CSS Inline#
CSS inline allows you to directly use [[${...}]]
in <style>
to get the value of the expression inside. When using, you need to enable CSS inline support by using th:inline="css"
in <style>
. The usage is as follows:
<!--Enable CSS inline-->
<style th:inline="css">
/*Set the font color of the element corresponding to idName*/
#[[${idName}]]{
/*CSS natural template*/
color:/*[(${color})]*/ #0000FF;
}
</style>
<!--CSS inline-->
<li><span>CSS inline:</span><span id="css">Test CSS inline</span></li>
In the above code, the backend will pass in the values of idName
and color
, allowing for dynamic CSS styling.
Testing Effects#
For specific code, you can click to read the original text to view the corresponding source code.