1. 程式人生 > >基於springboot框架的thymeleaf入門

基於springboot框架的thymeleaf入門

基於springboot框架的thymeleaf入門

一、什麼是Thymeleaf?

此處可參考博文

Thymeleaf是一個模板引擎,可以完全替代jsp,類似的模板引擎還有Velocity/FreeMarker。
ThymeLeaf的主要特點:
  • 有網路和無網路環境下均可執行
    前端可以檢視頁面的靜態效果,瀏覽器解析html時會忽略未定義的標籤屬性;
    後臺可以檢視帶資料的動態頁面,當有資料返回到頁面時,Thymeleaf標籤會動態地替換掉靜態內容。

  • 開箱即用
    它提供標準和spring標準兩種語言,可以直接套用模板實現JSTL、 OGNL表示式效果,避免每天套模板、該jstl、改標籤的困擾。同時開發人員也可以擴充套件和建立自定義的語言。

  • **提供spring標準語言和一個與springmvc完美整合的可選模組,快速實現表單繫結、屬性編輯器、國際化等功能

二、thymeleaf需要配置什麼?

1. 引入所依賴的jar

在springboot配置檔案pom.xml中新增thymeleaf所依賴:

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

2. 配置thymeleaf檢視解析器

在springboot中找到application.properties檔案,在此檔案中新增thymeleaf檢視解析器:

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

3. 常用語法

  1. 建立html
    需要在.html檔案中新增,只有添加了詞條語句,下文中才能正確使用th等標籤:
	<html xmlns:th="http://www.thymeleaf.org">
	```

2. 獲取變數值“${}”
```html
       <!--p中原有的值“333”只是為了給前端開發時做展示用的。
       thymeleaf有一個特性:在無網路的情況下也可以執行,只是執行出來的介面展示的是模擬資料,由此便很好做到了前後端分類,便於開發。-->
   <p th:text="'Hello!, ' + ${name} + '!'">3333</p>
  1. 選擇變量表達式“*{}”
 <div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Tom</span>.</p>
    <p>Surname: <span th:text="*{lastName}">Ford</span>.</p> 
</div> 
下面這種方式與上一中等價:
<div>
    <p>Name: <span th:text="${session.user.firstName}">Tom</span>.</p> 
    <p>Surname: <span th:text="${session.user.lastName}">Ford</span>.</p> 
</div>
  1. 連結表示式
<a th:href="@{/logout}" class="signOut"></a>
  1. 文字替換
<span th:text="'Welcome to my world, ' + ${user.name} + '!'">

想要更詳細瞭解thymeleaf各種標籤,可查閱此博文link.