Thymeleaf常用語法:使用星號表達式


在處理模板時,一般情況都是使用變量表達式 ${...} 來顯示變量,還可以使用選定對象表達式 *{...},它也稱為星號表達式。
如果在模板中先選定了對象,則需要使用星號表達式。Thymeleaf的內置對象#object效果等同於星號表達式。

開發環境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8

新建一個名稱為demo的Spring Boot項目。

1、pom.xml
加入Thymeleaf依賴

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

2、src/main/java/com/example/demo/User.java

package com.example.demo;

public class User {
    Integer id;
    String name;

    public User(Integer id, String name) {
        this.id = id;
        this.name = name;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

3、src/main/java/com/example/demo/TestController.java

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
public class TestController {
    @RequestMapping("/")
    public String test(Model model){
        List<User> users = queryUsers();
        model.addAttribute("user", users.get(0));
        model.addAttribute("users", users);
        return "test";
    }

    private List<User> queryUsers(){
        List<User> users = new ArrayList<User>();
        users.add(new User(1,"張三"));
        users.add(new User(2,"李四"));
        users.add(new User(3,"王五"));
        return users;
    }
}

4、src/main/resources/templates/test.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        table { border-collapse:collapse;}
        td { border: 1px solid #C1DAD7;}
    </style>
</head>
<body>
    <div>使用變量表達式</div>
    <table>
        <tr>
            <td th:text="${user.id}"></td>
            <td th:text="${user.name}"></td>
        </tr>
    </table>

    <div>使用星號表達式:使用星號</div>
    <table>
        <tr th:object="${user}">
            <td th:text="*{id}"></td>
            <td th:text="*{name}"></td>
        </tr>
    </table>

    <div>使用星號表達式:使用#object對象</div>
    <table>
        <tr th:object="${user}">
            <td th:text="${#object.id}"></td>
            <td th:text="${#object.name}"></td>
        </tr>
    </table>

    <div>在循環體中使用星號表達式</div>
    <table>
        <tr th:each="u : ${users}" th:object="${u}">
            <td th:text="*{id}"></td>
            <td th:text="*{name}"></td>
        </tr>
    </table>


</body>
</html>

 

瀏覽器訪問:http://localhost:8080
顯示如下截圖所示:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM