thymeleaf3.0學習


一、th屬性

1、th:text:設置當前元素的文本內容,類似修改制定屬性的還有th:utext,區別在於后者不會轉義html標簽
2、th:value:設置當前元素的value值,類似的還有th:src、th:href
3、th:each:循環遍歷元素;th:each="item : ${collection}",然后使用th:text="${item}"賦值表達式給標簽賦值。
4、th:if:條件判斷,類似th:unless,th:switch,th:case。判斷不為空才顯示th:if="${not #strings.isEmpty(result)}"
5、th:insert:代碼塊引入,類似的有th:replace,th:include;th:insert插入到當前標簽下,th:insert:保留自己的主標簽,保留th:fragment的主標簽。tth:replace:不要自己的主標簽,保留th:fragment的主標簽。th:include:不要自己的主標簽,保留th:fragment的主標簽。(官方3.0后不推薦使用)。
6、th:fragment:定義代碼塊
7、th:object:聲明變量,一般和*{}一起配合使用

二、注意

1、聲明名稱空間:`xmlns:th="http://www.thymeleaf.org`
2、設置文本內容th:text,設置input的值th:value,循環輸出th:each,條件判斷th:if,插入代碼塊th:insert,定義代碼塊th:fragment,聲明變量th:object
3、th:each放在需要被循環的標簽上。
4、變量表達式中提供了很多的內置方法,該內置方法是用#開頭,請不要與#{}消息表達式弄混。
5、th:insert、th:replace、th:include三種插入代碼塊的效果相似,但區別很大。

三、標准表達式語法

 1、${...}:變量表達式
    常見的內置對象
    ①ctx:上下文對象 ②vars:上下文變量 ③locale:上下文的語言對象 ④request:獲取HttpServletRequest對象
    ④response:獲取HttpServletResponse對象 ⑤session:獲取HttpSession對象 ⑥獲取ServletContext對象
    常用的內置方法
    ①strings:字符串格式化方法,如equals、equalsIgnoreCase、length、trim、toUpperCase、toLowerCase、
    indexOf、substring、replace、startWith、endsWith、contains、containsIgnoreCase等
    ②numbers:formatDecimal
    ③bools:isTrue、isFalse
    ④arrays:toArray,length,isEmpty,contains,containsAll等
    ⑤list、sets:toList,size,isEmpty,contains,containsAll,sort等
    ⑥maps:size,isEmpty,containsKey,containsValue等
    ⑦dates:format,year,month,hour,createNow等

2、@{...}:鏈接表達式
    可以動態獲取項目路徑

3、#{...}:消息表達式

4、~{...}:代碼塊表達式
    支持兩種語法結構
    推薦:~{templatename::fragmentname}
    支持:~{templatename::#id}

5、*{...}:選擇變量表達式
    多用於和th:object結合使用

四、thymeleaf在SpringBoot應用

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
  <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
  <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>
<dependencies>
  <dependency> 
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
</dependencies>

    有時候可能需要引入依賴
<dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
    <version>1.9.15</version>
</dependency>

    application.properties加入設置:
    spring.thymeleaf.cache=false
    spring.thymeleaf.mode=LEGACYHTML5


免責聲明!

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



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