thymeleaf模板使用詳解


1.引入依賴

maven中直接引入

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

 

可以查看依賴關系,發現spring-boot-starter-thymeleaf下面已經包括了spring-boot-starter-web,所以可以把spring-boot-starter-web的依賴去掉.

2.配置視圖解析器

spring-boot很多配置都有默認配置,比如默認頁面映射路徑為 
classpath:/templates/*.html 
同樣靜態文件路徑為 
classpath:/static/

在application.properties中可以配置thymeleaf模板解析器屬性.就像使用springMVC的JSP解析器配置一樣

// thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
// 開發時關閉緩存,不然沒法看到實時頁面
spring.thymeleaf.cache=false
// thymeleaf end

 

3.效果

這里寫圖片描述

4.基礎語法

回味上面的DEMO,可以看出來首先要在改寫html標簽

<html xmlns:th="http://www.thymeleaf.org">

 

這樣的話才可以在其他標簽里面使用th:*這樣的語法.這是下面語法的前提.

1.獲取變量值

<p th:text="'Hello!, ' + ${name} + '!'" >3333</p>

 

 

可以看出獲取變量值用$符號,對於javaBean的話使用變量名.屬性名方式獲取,這點和EL表達式一樣.

另外$表達式只能寫在th標簽內部,不然不會生效,上面例子就是使用th:text標簽的值替換p標簽里面的值,至於p里面的原有的值只是為了給前端開發時做展示用的.這樣的話很好的做到了前后端分離.

2.引入URL

Thymeleaf對於URL的處理是通過語法@{…}來處理的

<a th:href="@{http://blog.csdn.net/u012706811}">絕對路徑</a>
<a th:href="@{/}">相對路徑</a>
<a th:href="@{css/bootstrap.min.css}">Content路徑,默認訪問static下的css文件夾</a>

 

 

類似的標簽有:th:hrefth:src

3.字符串替換

很多時候可能我們只需要對一大段文字中的某一處地方進行替換,可以通過字符串拼接操作完成:

<span th:text="'Welcome to our application, ' + ${user.name} + '!'">

 

 

一種更簡潔的方式是:

<span th:text="|Welcome to our application, ${user.name}!|">

 

當然這種形式限制比較多,|…|中只能包含變量表達式${…},不能包含其他常量、條件表達式等。

4.運算符

在表達式中可以使用各類算術運算符,例如+, -, *, /, %

th:with="isEven=(${prodStat.count} % 2 == 0)"

 

 

邏輯運算符>, <, <=,>=,==,!=都可以使用,唯一需要注意的是使用<,>時需要用它的HTML轉義符

th:if="${prodStat.count} &gt; 1"
th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"

 

 

5.條件

if/unless

Thymeleaf中使用th:if和th:unless屬性進行條件判斷,下面的例子中,標簽只有在th:if中條件成立時才顯示:

<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

 

 

th:unless於th:if恰好相反,只有表達式中的條件不成立,才會顯示其內容。

Switch

Thymeleaf同樣支持多路選擇Switch結構:

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
</div>

 

 

默認屬性default可以用*表示:

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p>
</div>

 

 

6.循環

渲染列表數據是一種非常常見的場景,例如現在有n條記錄需要渲染成一個表格

,該數據集合必須是可以遍歷的,使用th:each標簽:

 

<body>
  <h1>Product list</h1>

  <table>
    <tr>
      <th>NAME</th>
      <th>PRICE</th>
      <th>IN STOCK</th>
    </tr>
    <tr th:each="prod : ${prods}">
      <td th:text="${prod.name}">Onions</td>
      <td th:text="${prod.price}">2.41</td>
      <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
    </tr>
  </table>

  <p>
    <a href="../home.html" th:href="@{/}">Return to home</a>
  </p>
</body>

 

 

 

 

可以看到,需要在被循環渲染的元素(這里是)中加入th:each標簽,其中th:each=”prod : ${prods}”意味着對集合變量prods進行遍歷,循環變量是prod在循環體中可以通過表達式訪問。

7.Utilities

為了模板更加易用,Thymeleaf還提供了一系列Utility對象(內置於Context中),可以通過#直接訪問:

  • #dates
  • #calendars
  • #numbers
  • #strings
  • arrays
  • lists
  • sets
  • maps
  •  
    下面用一段代碼來舉例一些常用的方法:
  • ${#dates.format(date, 'dd/MMM/yyyy HH:mm')}
    ${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}
    ${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}
    ${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}
    
    /*
     * Create a date (java.util.Date) object for the current date and time
     */
    ${#dates.createNow()}
    
    /*
     * Create a date (java.util.Date) object for the current date (time set to 00:00)
     */
    ${#dates.createToday()}

     

string

/*
 * Check whether a String is empty (or null). Performs a trim() operation before check
 * Also works with arrays, lists or sets
 */
${#strings.isEmpty(name)}
${#strings.arrayIsEmpty(nameArr)}
${#strings.listIsEmpty(nameList)}
${#strings.setIsEmpty(nameSet)}

/*
 * Check whether a String starts or ends with a fragment
 * Also works with arrays, lists or sets
 */
${#strings.startsWith(name,'Don')}                  // also array*, list* and set*
${#strings.endsWith(name,endingFragment)}           // also array*, list* and set*

/*
 * Compute length
 * Also works with arrays, lists or sets
 */
${#strings.length(str)}

/*
 * Null-safe comparison and concatenation
 */
${#strings.equals(str)}
${#strings.equalsIgnoreCase(str)}
${#strings.concat(str)}
${#strings.concatReplaceNulls(str)}

/*
 * Random
 */
${#strings.randomAlphanumeric(count)}

 

快速的學習還是直接寫例子最快,后期寫Demo遇到問題再加上去

補充

在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>


免責聲明!

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



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