SpringBoot之模板引擎


一、Thymeleaf

1.1 集成 templates

pom.xml 文件中添加依賴

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

application.yml 文件中添加配置

spring:
  thymeleaf:
    # 模板文件前綴
    prefix: classpath:/templates/
    # 模板文件后綴
    suffix: .html

​ 注:這些屬性是 ThymeleafProperties 默認的配置,如果不需要變更的話可以不用配置。

1.2 實例

java目錄下新建 HelloController.java 文件

@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello(Model model) {
        // 普通文本
        model.addAttribute("text","MarkLogZhu");
        // 普通類型數組
        int[] array = new int []{10,2,33,4,5};
        model.addAttribute("array", array);
        // 對象列表
        List<User> users = new ArrayList<>();
        users.add(new User(1,"張三"));
        users.add(new User(2,"李四"));
        users.add(new User(3,"王五"));
        model.addAttribute("users", users);
        return "hello";
    }
    
}

templates 目錄下新建 hello.html 文件

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>SpringBoot-thymeleaf demo</title>
</head>
<body>
<p th:text="'hello, ' + ${text} + '!'"/>

<table>
    <tr th:each=" arr : ${array}">
        <td th:text="${arr}">序號</td>
    </tr>
</table>


<table>
    <thead>
    <th>序號</th>
    <th>用戶 id</th>
    <th>用戶名</th>
    </thead>
    <tbody>
    <tr th:each=" user,userStat : ${users}">
        <td th:text="${userStat.index+1}">序號</td>
        <td th:text="${user.userId}">用戶 id</td>
        <td th:text="${user.userName}">用戶名</td>
    </tr>
    </tbody>
</table>


</body>
</html>

啟動項目,在瀏覽器訪問:http://localhost:8080/hello

1.3 常用語法

關鍵字 功能介紹
th:id 替換id
th:text 文本替換
th:utext 支持html的文本替換
th:object 替換對象
th:value 屬性賦值
th:with 變量賦值運算
th:style 設置樣式
th:onclick 點擊事件
th:each 屬性賦值
th:if 判斷條件
th:unless 和th:if判斷相反
th:href 鏈接地址
th:switch 多路選擇 配合th:case 使用
th:case th:switch的一個分支
th:fragment 布局標簽,定義一個代碼片段,方便其它地方引用
th:include 布局標簽,替換內容到引入的文件
th:replace 布局標簽,替換整個標簽到引入的文件
th:selected selected選擇框 選中
th:src 圖片類地址引入
th:inline 定義js腳本可以使用變量
th:action 表單提交的地址
th:remove 刪除某個屬性
th:attr 設置標簽屬性,多個屬性可以用逗號分隔

更多語法請參考 thymeleaf 官方文檔


免責聲明!

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



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