Thymeleaf語法


一、前言

  • Thymeleaf 是什么?
    Thymeleaf 是 Web 和獨立環境的現代服務器端 Java 模板引擎,能夠處理HTML,XML,JavaScript,CSS 甚至純文本。
  • 什么是模板引擎?
    模板引擎(這里特指用於Web開發的模板引擎)是為了使用戶界面與業務數據(內容)分離而產生的,它可以生成特定格式的文檔,用於網站的模板引擎就會生成一個標准的HTML文檔。
  • 類似的模板引擎有哪些?
    市面上主流的 Java 模板引擎有:JSP、Velocity、Freemarker、Thymeleaf
  • 模板引擎的作用:
    將靜態頁面和業務數據進行整合,由服務器端渲染之后返回客戶端進行顯示。不同的模板引擎的區別在於使用不同的語法。
  • 自我認知
    jspthymeleaf,再到vue,這是一個前后端逐漸分離的過程。jsp的特點是頁面中可以嵌套java代碼,這顯然很強大,但導致的結果是頁面邏輯(一些前端界面元素的顯示隱藏,以及動態變化)和業務邏輯(一些需要訪問后台的操作,如數據庫查詢)常常糾纏在一起,代碼混亂不堪,可維護性差,前后台人員職責分工不明確,責任難以追蹤。到了thymeleaf,情況好了很多,因為thymeleaf支持html界面,無論是不是在服務器環境下,界面都能展示,在界面上直接與后台交互的情況也少了很多。再到現在很火的vue,才算實現了真正意義上的前后端分離,前端人員專注於前台界面,后端人員專注於后台接口。

二、SpringBoot環境下使用thymeleaf

Springboot整合thymeleaf很簡單,下面只介紹下幾個步驟:
1.導入依賴

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

2.簡單配置 application.properties

spring.thymeleaf.enabled=true
spring.thymeleaf.cache=false
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.mode=HTML
spring.thymeleaf.suffix=.html

3.在html界面引入名稱空間

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    ......
</html>

三、語法詳解

thymeleaf語法都是html標簽加th:*的形式

1、 文本操作
//輸出字符串 thymeleaf
<h2 th:text="'thymeleaf'"></h2>
//輸出字符串 thymeleaf
<h2 th:utext="'thymeleaf'"></h2>

th:text和th:utext的區別:

th:utext中的html標簽會正常翻譯成html標簽,而th:text的內容原樣輸出。如下:

<p th:text="'hello <b>thymeleaf</b>'"></p> //原樣輸出
<p th:utext="'hello <b>thymeleaf</b>'"></p>  //thymeleaf加粗

輸出包含空格的文本:

<h2 th:text="'thymeleaf home page'"></h2>
<h2 th:utext="|thymeleaf home page|"></h2>

所有th:標簽都可以用data-th-替換:

<h2 data-th-text="|thymeleaf home page|"></h2>
<h2 data-th-utext="|thymeleaf home page|"></h2>
2、幾種常用符號

#號用於國際化
1.在templates文件夾下建立i18n目錄,新建messages_zh_CN.properties文件,內容如下:

thymeleaf.welcome=welcome to thymeleaf index page

2.在application.properties中配置:

spring.messages.basename=i18n/messages

3.在界面中使用:

<p th:text="#{thymeleaf.welcome}"></p>

$用於后端取值

后端要向model存入user對象

<div th:text="${user.name}"></div>

* 用於綁定一個對象的屬性,與$結合使用

<span th:object="${human}">
    姓名:<span th:text="*{name}"></span> <br>
    愛好:<span th:text="*{favorite}"></span> <br>
    國籍:<span th:text="*{nationality}"></span> <br>
</span>

@用於鏈接

<!--引入static/css目錄中的thymeleaf.css -->
<link rel="stylesheet" href="../static/css/thymeleaf.css" th:href="@{/css/thymeleaf.css}">

<!--超鏈接 最終路徑為/user/find?username=id-->
<a th:href="@{/user/find(username=${human.name})}">查找用戶</a> 

<!--最終路徑為:/user/find/具體的username-->
<a th:href="@{/user/find/{username}(username=${human.name})}">查找用戶</a> <br>

~用於取到項目根路徑

<a th:href="@{~/user/find/jack}">查找用戶</a>
3、操作html元素
<!--修改value屬性-->
<input type="submit" value="提交" th:value="submit">
<br>

<!--等價於-->
<input type="submit" value="提交" th:attr="value='submit'">
<hr>

<!--除了th:value還有很多其它html元素的屬性都可用。-->

<!--追加樣式一個addStyle樣式-->
<input type="text" class="originStyle" th:classappend="'addStyle'">
<hr>

<!--設置選擇狀態-->
<input type="checkbox" th:checked="${isChecked}">

4、幾種表達式
  • 三元表達式
<div th:object="${user}">
    <div th:text="*{username} == null ? 'username is not defined' : *{username}"></div>
</div>

三元表達式省略寫法,表達式為真,值為*{favorite},否則,值為后面的字符串

<div th:object="${user}">
    <div th:text="*{username}?:'username attribute is not defined'"></div>
</div>

三元表達式省略寫法,表達式為真,會給標簽加上customStyle樣式,為假,返回null,什么也不執行

<div th:class="${customStyleOn} ? 'customStyle'"></div>
  • switch表達式
<div th:switch="${usernames.get(1)}">
    username:
    <p th:case="'Lorem'">lorem</p>
    <p th:case="'ipsum'">ipsum</p>
    <p th:case="'dolor'">dolor</p>
    <p th:case="*">whatever</p>  <!--都不匹配時執行-->
</div>
5、條件判斷、算數運算
<!--用#引用內置對象判斷字符串是否為空-->
<div th:if="${not #strings.isEmpty('lorem')}">lorem</div>

<div th:unless="${ #strings.isEmpty('lorem')}">lorem</div>

<div th:text="33 + 22"></div>

<div th:text="${number} + 22 > 30"></div>
6、循環迭代
<ul>
   <!--遍歷user對象,如果是第偶數個則加上自定義樣式,如果是奇數,加上詳情連接-->
    <li th:each="user : ${users}" th:classappend="${userStat.even}?'m-list-even'">
        <span th:text="${user}"></span>
        <a th:href="@{/user/find/{username}(username=${user})}" th:if="${userStat.odd}">view detail</a>
    </li>
</ul>
7、fragment的使用

fragment類似於jsp的jsp:include,用於重用一些頁面。
在templates目錄下建立一個footer.html用於存放通用的版權片段:內容如下:

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!--copyright是片段的名字-->
<footer th:fragment="copyright">
    <div>
        &copy;2019-2020 Designed by Oamha, Glad to receive your reply
    </div>
</footer>
</html>

下面就可以將其引入到其它界面中了:

<!--footer是片段所在的文件名,copyright是片段名-->
<div th:insert="footer :: copyright"></div>

<!--上面等價於-->
<div th:insert="~{footer :: copyright}"></div>

<!--引入片段也可以用th:replace-->
<div th:replace="footer :: copyright"></div>

<!--還可以用th:include-->
<div th:include="footer :: copyright"></div>
  • th:insert保留當前頁面的div根標簽,也保留copyright片段的footer根標簽
  • th:replace只保留copyright片段的footer根標簽,div被替換掉了
  • th:include保留當前界面的div,但只包含copyright片段的里的內容,不再包含footer根標簽

片段還可以傳參數:比如有一個navbar片段,所在文件templates/nav.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<div th:fragment="navbar(span, role, username)">
    <span th:replace="${span}"></span>
    <span th:text="${role}"></span>
    <span th:text="${username}"></span>
</div>
</html>

在其他界面引入:

<!--第一個參數傳入當前界面的span標簽,第二個參數是字符串,第三個參數代表什么也不傳-->
<div th:replace="nav :: navbar (~{::span}, 'admin', _)">
    <span>這個span將替換片段中的span</span>
</div>
  • 傳當前界面的標簽也可以用 ~{this:span}
  • 什么也不傳另一種寫法為 ~{}
8、注釋
<table>
    <!--/*/<th:block th:each="user : ${users}">/*/-->
        <tr>
            <td th:text="${user}">oamha</td>
        </tr>
    <!--/*/</th:block>/*/-->
</table>
  • thymeleaf注釋格式為 <!--/*/內容/*/-->
  • 內容部分在瀏覽器直接打開時會被當成注釋,只有在服務器環境下才會被模板引擎正確解析
9、行內表達式
<th:block th:with="str='hello <strong>thymeleaf</strong>'">
    <p>[[${str}]]</p>
    <p>[(${str})]</p>
</th:block>
  • th:block 相當於一個容器,但是不會產生具體的標簽
  • th:with 為str變量賦值
  • [[]]相當於th:text
  • [()]相當於th:utext

有時我們需要在JavaScript代碼中訪問session中的
值,也可以用行內表達式

<!--取出session中的user-->
<script th:inline="javascript">
    var user = [[${session.user}]]
</script>

四、總結

thymeleaf的常用語法就這些,還有一些內置對象的使用,遇到的話可以查閱文檔。


免責聲明!

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



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