[Spring Boot] Thymeleaf template engine - syntax of expressions

syntax of expressions

The main function of the template is to render the data returned by the background into HTML. So how does Thymeleaf parse the background data? Next, learn the syntax supported by Thymeleaf expressions from the aspects of variables, methods, conditional judgments, loops, and operations (logical operations, Boolean operations, comparison operations, and conditional operations).

1. Assignment and splicing

(1) Text assignment

Assignment is to replace the data returned by the background into the page through the ${} tag.

<p th:text="${name}">hello spring boot</p>

(2) Text splicing

Thymeleaf supports splicing the value returned by the background with the existing content, and then replacing it into the page. The sample code is as follows:

<span th:text=" 'Welcome,' + ${username} + '!' "></span>

In the above example, the value of userName returned by the background is spliced ​​after "Welcome," and finally replaced in the page <span>. Text literals can be enclosed in single quotes, and special characters need to be escaped with "\".

In addition to the above writing method, there is another concise way of writing string concatenation:

<span th:text="|Welcome, + ${username} + !|"></span>

In the above example, two vertical bars "|" are used to merge the data returned by the background with the content in the page.

The Thymeleaf tag is basically the same as HTML. Adding "th:" to the HTML tag can replace the value of the native attribute in the HTML tag.

2. Condition judgment

Thymeleaf uses th:if and th:unless attributes for conditional judgment. Use the th:if attribute in the label to judge whether the expression is true, if it is true, the content of the label will be displayed, and if it is not true, the content of the label will be hidden. th:unless is just the opposite of th:if, and its content will be displayed only if the condition in the expression is not true.

The results of th:if and th:unless expressions support boolean, number, character, string and other types. The following example demonstrates how to use th:if and th:unless attributes in Thymeleaf for conditional judgment.

Step 01 defines the HTML page.

Create the if.html page in the templates directory, the sample code is as follows:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Thymeleaf模板引擎</h1>
<h3>条件判断</h3>
<a th:if="${flag == 'yes'}" th:href="@{http://www.a.home/}">a.home</a>
<a th:unless="${flag != 'no'}" th:href="@{http://www.b.home/}">b.home</a>
</body>
</html>

In the above example, the conditional judgment is performed through the th:if tag. If flag==yes, the link of a.home is displayed, otherwise the link of b.home is displayed.

Step 02 defines the backend interface and returns data results.

    @RequestMapping("/if")
    public String ifunless(ModelMap map) {
    
    
        map.addAttribute("flag","yes");
        return "if";
    }

In the above example, the URL of the request is defined, the if.html page is returned, and the value of the flag is yes.

Step 03 starts verification.

After starting the project, enter the address http://localhost:8080/if in the browser, as shown in the figure.
insert image description here
It can be seen from the figure that the flag value returned by the backend is yes, th:if="${flag == 'yes'}"and the condition is met, so the link of a.home is displayed. And th:unless="${flag != 'no'}"the condition is also established, so the link of b.home is hidden.

3.switch

Thymeleaf uses th:switch and th:case tags to judge multiple conditions, which is equivalent to the switch statement in Java, and displays the matching content according to the conditions. If there are multiple matching results, only the first one is selected for display. th:case="*"Indicates the default option, that is, th:case="*"the content displayed when the value of no case is true, corresponding to the default of switch in Java. The following uses the data state as an example to demonstrate the usage of th:switch.

Step 01 Create the front-end page.

Create a switch.html page in the templates directory, the sample code is as follows:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"></meta>
    <title>Example switch</title>
</head>
<body>
<h1>Thymeleaf模板引擎</h1>
<h3>switch</h3>
<div>
    <div th:switch="${status}">
        <p th:case="'todo'">未开始</p>
        <p th:case="'doing'">进行中</p>
        <p th:case="'done'">完成</p>
        <!-- *case的默认选项 -->
        <p th:case="*">状态错误</p>
    </div>
</div>
</body>
</html>

In the sample code above, use th:switch and th:case tags to display matching data according to the value of status returned by the background.

Step 02 Add a backend program.

    @RequestMapping("/switch")
    public String ifunless(ModelMap map) {
    
    
        map.addAttribute("status","doing");
        return "switch";
    }

In the above example, the switch.html page is returned in the background, and the status value of doing is returned at the same time.

Step 03 Run the verification.

Start the project, enter the address http://localhost:8080/switch in the browser, and the page display effect is as shown in the figure. The page displays the status of "in progress", and you can change the value of status in the background to view the results.

insert image description here
As can be seen from the figure, the switch.html page displays different content through the status value returned by the background.

4. Loop through

Loop traversal is commonly used in daily projects, and is generally used to render the data returned from the background to the front-end table. Thymeleaf can use the th:each tag to iterate and loop data, syntax: th:each="obj,iterStat:${objList}", supports List, Map, array data types, etc. The following is a simple example to demonstrate the process of data loop traversal.

Step 01 defines the backend data.

First define a user list on the backend, and then pass it to the frontend page:

    @RequestMapping("/list")
    public String list(ModelMap map) {
    
    
        List<User> list = new ArrayList();
        User user1 = new User("spring", 12, "123456");
        User user2 = new User("boot", 6, "123456");
        User user3 = new User("Thymeleaf", 68, "123456");
        list.add(user1);
        list.add(user2);
        list.add(user3);
        map.addAttribute("user", list);
        return "list";
    }

In the above sample code, the background returns the list.html page, and at the same time returns the user list data of the ArrayList type.

Step 02 Create the front page.

Create a list.html page in the templates directory to display background data. The sample code is as follows:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"></meta>
    <title>Example switch</title>
</head>
<body>
<h1>Thymeleaf模板引擎</h1>
<h3>each循环遍历</h3>
<div>
    <table>
        <tr>
            <th>姓名</th>
            <th>年龄</th>
            <th>密码</th>
            <th>变量: index</th>
            <th>变量: count</th>
            <th>变量: size</th>
            <th>变量: even</th>
            <th>变量: odd</th>
            <th>变量: first</th>
            <th>变量: last</th>
        </tr>
        <tr th:each="user,stat : ${users}">
            <td th:text="${user.name}">name</td>
            <td th:text="${user.age}">age</td>
            <td th:text="${user.password}">password</td>
            <td th:text="${iterStat.index}">index</td>
            <td th:text="${iterStat.count}">count</td>
            <td th:text="${iterStat.size}">size</td>
            <td th:text="${iterStat.even}">even</td>
            <td th:text="${iterStat.odd}">odd</td>
            <td th:text="${iterStat.first}">first</td>
            <td th:text="${iterStat.last}">last</td>
        </tr>
    </table>
</div>
</body>
</html>

Loop traversal is realized through th:each, syntax: th:each="obj,stat:${objList}".

1) ${users}is to get variables from the template context.

2) user is ${users}every object after variable traversal.

3) ${user.name}Variables in the traversal can be read.

While traversing, you can also get the iteration status variable stat of the iterative object, which contains the following attributes:

  • index: The index of the current iteration object (calculated from 0).
  • count: The index of the current iteration object (calculated from 1).
  • size: The size of the iterated object.
  • even/odd: Boolean value, whether the current cycle is even/odd (counting from 0).
  • first: Boolean value, whether the current loop is the first one.
  • last: Boolean value, whether the current loop is the last one.

Step 03 Run the verification.

Start the project, enter the address in the browser: http://localhost:8080/list, the page display effect is as shown in the figure.

insert image description here

As can be seen from the figure, the list data returned by the backend is looped through and displayed on the page, and the th:each tag also provides tags such as index and count.

5. Operators

Thymeleaf supports the use of various data calculation functions such as arithmetic operations, logical operations, Boolean operations, and trinocular operations in expressions, so that the front-end page can dynamically display page information according to the data returned by the background. Let's demonstrate one by one below.

5.1 Arithmetic operators

Arithmetic operators include +、-、*、/、%such simple calculations.

<th:with="isEven=(${prodStat.count} / 2 == 0)">

In the above example, parity is determined by the arithmetic operation of division by 2.

5.2 Relational Operators

Relational operators include >, <, >=, <=, ==, !=, and the corresponding aliases are gt, lt, ge, le, eq, ne. When using > and <, you need to use its HTML escape character. Therefore, it is recommended to use aliases such as gt and lt:

  • gt: great than (greater than).
  • ge: great equal (greater than or equal to).
  • eq: equal (equal to).
  • lt: less than (less than).
  • le: less equal (less than or equal to).
  • ne: not equal (not equal to).
<th:if="${prodStat.count} gt 1">

Use gt to compare whether the value of count is greater than 1.

5.3 Logical operators

Multiple conditional judgments are realized through logical operators, including && (and) and || (or).

&& (and) means "and", the example is as follows:

<div th:if="${age gt 10 && a lt 19}"></div>

or

<div th:if=" (${age gt 10}) and ${age lt 19} "></div>

The above example means: if age>10 and age <19, realize whether the age is between 10 and 19 years old.

|| or means "or", examples are as follows:

<div th:if="${age gt 10 || age lt 19}"></div>

or

<div th:if=" (${age gt 10}) or ${age lt 19} "></div>

The above example means: if age > 10 or age < 19, realize the judgment that the age is greater than 10 or younger than 19.

5.4 Ternary operator

The syntax of the ternary operator is similar to languages ​​such as Java, and the specific usage is as follows:

<tr th:class="${row.even}? 'even' : 'odd' ">
...
</tr>

In the above example, the data is rendered in the front-end list to achieve the effect of interlaced display with colors.

Guess you like

Origin blog.csdn.net/weixin_45627039/article/details/132095774