1. 程式人生 > 實用技巧 >SpringBoot整合Thymeleaf

SpringBoot整合Thymeleaf

Thymeleaf 是一個跟 Velocity、FreeMarker 類似的模板引擎,它可以完全替代 JSP 。也就是說JSP中的特性在Thymeleaf幾乎都有對應的支援。Thymeleaf支援HTML原型,通過Thymeleaf特殊的標籤可以基本實現JSP中動態資料的展示效果。

在前後端不分離的情況下Thymeleaf的資料繫結可以很好的節約工程師的時間

1.首先引入包的依賴

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

Thymeleaf 支援渲染HTML,因此通常我們使用的頁面模板也就是HTML,同時它需要遵循一定的規則:

  1. 比如在spring boot專案中,通常我們將Thymeleaf渲染的頁面放在resources/templates目錄下,這樣Thymeleaf會預設識別。

  2. 若想要在HTML頁面中使用Thymeleaf,需要修改<html lang="en"><html lang="en" xmlns:th="http://www.thymeleaf.org">

  3. 在spring boot專案中resources/static

    目錄下的檔案可通過瀏覽器直接訪問,而resources/templates下的HTML不能通過瀏覽器直接訪問,而需要Spring Mvc這樣的框架對映到那個頁面地址。

  4. 可意根據後臺傳參更好的實現頁面國際化

2.配置yml

spring:
  thymeleaf:
    cache: false
    prefix: classpath:/templates/
    suffix: .html
    encoding: UTF-8
    content-type: text/html
    mode: LEGACYHTML5

這裡mode不能配置為html5,配置後頁面會嚴格遵守html5的頁面特性。標籤必須完整

3.測試頁面:寫控制器、mapper、service、serviceimpl、mapper.xml實現一系列的資料操作

thymeleaf特性:

值得注意的是頁面可以和後臺一樣程式設計,當資料返回為arryList的時候也可以如後臺一般進行for迴圈操作

List<String> list = new ArrayList<>();
list.add("list1");
list.add("list2");
list.add("list3");
model.addAttribute("list", list);

前端迴圈

<ol th:each="item,property: ${list}">
    <li th:text="${property.index}"></li>
    <li th:text="${item}"></li>
</ol>

property稱作狀態變數,屬性有:

  • index:當前迭代物件的index(從0開始計算)
  • count: 當前迭代物件的index(從1開始計算)
  • size:被迭代物件的大小
  • current:當前迭代變數
  • even/odd:布林值,當前迴圈是否是偶數/奇數(從0開始計算)
  • first:布林值,當前迴圈是否是第一個
  • last:布林值,當前迴圈是否是最後一個

thymeleaf還支援母版頁佈局,有時間可以去了解一下