1. 程式人生 > >SpringBoot整合Thymeleaf模板

SpringBoot整合Thymeleaf模板

1、新增起步依賴:

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

2、新增配置(application.properties):

#開發時關閉快取,不然沒法看到實時頁面
spring.thymeleaf.cache=false

參考ThymeleafProperties.java類,cache預設為true,其它屬性都有預設值,一般不需要修改。

3、寫測試controller返回頁面並攜帶資料:

package cn.mmweikt.es.controller;

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

@Controller
public class IndexController {
    @GetMapping("/index")
    public String indexPage(Model model) {
        model.addAttribute("name", "es_project.");
        return "index";
    }
}

4、在resources/templates下放.html頁面,在resources/static下放靜態檔案。templates和static下都可以再放資料夾:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <span th:text="${name}"></span>
</body>
</html>

注意,在html標籤裡一定要引入 xmlns:th="http://www.thymeleaf.org" ,這樣thymeleaf模板才會啟用,才能使用th:*這樣的語法。
語法可參考:
https://www.cnblogs.com/jin-zhe/p/8202885.html
https://www.cnblogs.com/nfcm/p/7843935.html

補充:
網上看到說,在spring-boot1.4之後,支援thymeleaf3,可以更改版本號來進行修改支援。3相比2極大的提高了效率,並且不需要標籤閉合,類似的link,img等都有了很好的支援,按照如下配置即可:

 <properties>
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     <!-- set thymeleaf version -->
     <thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
     <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
     <!--set java version-->
     <java.version>1.8</java.version>
  </properties>