解讀thymeleaf模板引擎中th:if的使用
thymeleaf模板引擎中th:if的使用
th:if 條件判斷
很多時(shí)候只有在滿?某個(gè)條件時(shí),才將?個(gè)模板?段顯示在結(jié)果中,否則不進(jìn)行顯示。比如只有當(dāng)用戶有訂單時(shí),才為它顯示訂單鏈接,否則不顯示。th:if 屬性用于滿足這個(gè)需求
<body>
<!--if屬性結(jié)果為 true,模板會(huì)進(jìn)行顯示-->
<p th:if="true">th:if="true"</p>
<!--if屬性結(jié)果為 false,模板不會(huì)進(jìn)行顯示-->
<p th:if="false">th:if="false"</p>
<!--后臺(tái)控制器傳出數(shù)據(jù):model.addAttribute("isMarry", true);-->
<p th:if="${isMarry}">已婚</p>
</body>th:if 屬性不僅只以布爾值作為判斷條件,它將按照如下規(guī)則判定指定的表達(dá)式結(jié)果為 true:
- 如果表達(dá)式結(jié)果為布爾值,則為 true 或 false
- 如果表達(dá)式的值為 null,th:if 將判定此表達(dá)式為 false
- 如果值是數(shù)字,為 0 時(shí),判斷為 false;不為零時(shí),判定為 true
- 如果值是是 String,值為 “false”、“off”、“no” 時(shí),判定為 false,否則判斷為 true,字符串為空時(shí),也判斷為 true
- 如果值不是布爾值,數(shù)字,字符或字符串的其它對(duì)象,只要不為 null,則判斷為 true
<body>
<!--表達(dá)式的結(jié)果為布爾類型時(shí),if 直接以它為結(jié)果-->
<p th:if="true">th:if="true"</p>
<!--當(dāng)表達(dá)式結(jié)果為null時(shí),則if判定為false-->
<p th:if="null">th:if="null"</p>
<!--表達(dá)式為數(shù)字時(shí),不為0,if判定為true,為0,時(shí),if判定為false-->
<p th:if="11">th:if="11"</p>
<p th:if="0">th:if="0"</p>
<!--表達(dá)式結(jié)果為字符串時(shí),如果為 true,則if判定為true;值為 false,則if判定為false-->
<!--結(jié)果為 off、no 等特殊字符串時(shí),if 判定為false-->
<p th:if="'true'">th:if="'true'"</p>
<p th:if="'false'">th:if="'false'"</p>
<p th:if="'off'">th:if="'off'"</p>
<p th:if="'no'">th:if="'no'"</p>
<!--表達(dá)式結(jié)果字符串不為false,off,no時(shí),if判定為true-->
<p th:if="'Love China'">th:if="'Love China'"</p>
<!--后臺(tái)傳輸:model.addAttribute("userList", User.getUsers());-->
<!--只要 userList 不等于null,則if判定為true,否則為false-->
<p th:if="${userList}">th:if="${userList}"</p>
<!--后臺(tái)傳輸:model.addAttribute("name", "");-->
<!--字符串為空時(shí),if判定為 true-->
<p th:if="${name}eq''">name 等于空</p>
<p th:if="${name}">th:if="${name}"</p>
</body>
th:if 判斷表達(dá)式
gt:(大于)>ge:(大于等于)>=eq:(等于)==lt:(小于)<le:(小于等于)<=ne:(不等于)!=
Thymeleaf模板引擎語(yǔ)法使用
1、模板引擎thymeleaf使用
引入依賴:
<dependency>? ? ? <groupId>org.springframework.boot</groupId>? ? ? <artifactId>spring-boot-starter-thymeleaf</artifactId>? </dependency>
頁(yè)面導(dǎo)入頭部文件:
<html xmlns:th="http://www.thymeleaf.org">
語(yǔ)法說(shuō)明:
Thymeleaf通過(guò) ${}來(lái)獲取model中的變量,注意這不是el 表達(dá)式,而是ognl表達(dá)式,但是語(yǔ)法非常像。
2、ognl表達(dá)式的語(yǔ)法糖
剛才獲取變量值,我們使用的是經(jīng)典的對(duì)象.屬性名方式。但有些情況下,我們的屬性名可能本身也是變量,怎么辦?
ognl提供了類似js的語(yǔ)法方式:
例如:${user.name} 可以寫作${user['name']}
自定義變量
場(chǎng)景
看下面的案例:
<h2>
? ? <p>Name: <span th:text="${user.name}">Jack</span>.</p>
? ? <p>Age: <span th:text="${user.age}">21</span>.</p>
? ? <p>friend: <span th:text="${user.friend.name}">Rose</span>.</p>
</h2>我們獲取用戶的所有信息,分別展示。
當(dāng)數(shù)據(jù)量比較多的時(shí)候,頻繁的寫user.就會(huì)非常麻煩。
因此,Thymeleaf提供了自定義變量來(lái)解決:
示例:
<h2 th:object="${user}">
? ? <p>Name: <span th:text="*{name}">Jack</span>.</p>
? ? <p>Age: <span th:text="*{age}">21</span>.</p>
? ? <p>friend: <span th:text="*{friend.name}">Rose</span>.</p>
</h2>首先在 h2上 用 th:object="${user}"獲取user的值,并且保存
然后,在h2內(nèi)部的任意元素上,可以通過(guò) *{屬性名}的方式,來(lái)獲取user中的屬性,這樣就省去了大量的user.前綴了
3、拼接
我們經(jīng)常會(huì)用到普通字符串與表達(dá)式拼接的情況:
<span th:text="'歡迎您:' + ${user.name} + '!'"></span>字符串字面值需要用'',拼接起來(lái)非常麻煩,Thymeleaf對(duì)此進(jìn)行了簡(jiǎn)化,使用一對(duì)|即可:
<span th:text="|歡迎您:${user.name}|"></span>與上面是完全等效的,這樣就省去了字符串字面值的書寫。

4、運(yùn)算
需要注意:${}內(nèi)部的是通過(guò)OGNL表達(dá)式引擎解析的,外部的才是通過(guò)Thymeleaf的引擎解析,因此運(yùn)算符盡量放在${}外進(jìn)行。
算術(shù)運(yùn)算
支持的算術(shù)運(yùn)算符:+ - * / %
<span th:text="${user.age}"></span>
<span th:text="${user.age}%2 == 0"></span>
比較運(yùn)算
支持的比較運(yùn)算:>, <, >= and <= ,但是>, <不能直接使用,因?yàn)閤ml會(huì)解析為標(biāo)簽,要使用別名。
注意 == and !=不僅可以比較數(shù)值,類似于equals的功能。
可以使用的別名:gt (>), lt (<), ge (>=), le (<=), not (!). Also eq (==), neq/ne (!=).
條件運(yùn)算
三元運(yùn)算
<span th:text="${user.sex} ? '男':'女'"></span>三元運(yùn)算符的三個(gè)部分:conditon ? then : else
- ?
condition:條件 - ?
then:條件成立的結(jié)果 - ?
else:不成立的結(jié)果
其中的每一個(gè)部分都可以是Thymeleaf中的任意表達(dá)式。

默認(rèn)值
有的時(shí)候,我們?nèi)∫粋€(gè)值可能為空,這個(gè)時(shí)候需要做非空判斷,可以使用 表達(dá)式 ?: 默認(rèn)值簡(jiǎn)寫:
<span th:text="${user.name} ?: '二狗'"></span>當(dāng)前面的表達(dá)式值為null時(shí),就會(huì)使用后面的默認(rèn)值。
注意:?:之間沒(méi)有空格。

5、循環(huán)
循環(huán)也是非常頻繁使用的需求,我們使用th:each指令來(lái)完成:
假如有用戶的集合:users在Context中。
<tr th:each="user : ${users}">
<td th:text="${user.name}">Onions</td>
<td th:text="${user.age}">2.41</td>
</tr>${users}是要遍歷的集合,可以是以下類型:Iterable,實(shí)現(xiàn)了Iterable接口的類Enumeration,枚舉Interator,迭代器Map,遍歷得到的是Map.EntryArray,數(shù)組及其它一切符合數(shù)組結(jié)果的對(duì)象
在迭代的同時(shí),我們也可以獲取迭代的狀態(tài)對(duì)象:
<tr th:each="user,stat : ${users}">
<td th:text="${user.name}">Onions</td>
<td th:text="${user.age}">2.41</td>
</tr>stat對(duì)象包含以下屬性:
index,從0開始的角標(biāo)count,元素的個(gè)數(shù),從1開始size,總元素個(gè)數(shù)current,當(dāng)前遍歷到的元素even/odd,返回是否為奇偶,boolean值first/last,返回是否為第一或最后,boolean值
6、邏輯判斷
有了if和else,我們能實(shí)現(xiàn)一切功能_。
Thymeleaf中使用th:if 或者 th:unless ,兩者的意思恰好相反
<span th:if="${user.age} < 24">小鮮肉</span>如果表達(dá)式的值為true,則標(biāo)簽會(huì)渲染到頁(yè)面,否則不進(jìn)行渲染。
以下情況被認(rèn)定為true:
- 表達(dá)式值為true
- 表達(dá)式值為非0數(shù)值
- 表達(dá)式值為非0字符
- 表達(dá)式值為字符串,但不是"false","no","off"
- 表達(dá)式不是布爾、字符串、數(shù)字、字符中的任何一種
其它情況包括null都被認(rèn)定為false

7、分支控制switch
這里要使用兩個(gè)指令:th:switch 和 th:case
<div th:switch="${user.role}">
<p th:case="'admin'">用戶是管理員</p>
<p th:case="'manager'">用戶是經(jīng)理</p>
<p th:case="*">用戶是別的玩意</p>
</div>需要注意的是,一旦有一個(gè)th:case成立,其它的則不再判斷。與java中的switch是一樣的。
另外th:case="*"表示默認(rèn),放最后

頁(yè)面

8、JS模板
模板引擎不僅可以渲染html,也可以對(duì)JS中的進(jìn)行預(yù)處理。而且為了在純靜態(tài)環(huán)境下可以運(yùn)行,其Thymeleaf代碼可以被注釋起來(lái):
<script th:inline="javascript">
const user = /*[[${user}]]*/ {};
const age = /*[[${user.age}]]*/ 20;
console.log(user);
console.log(age)
</script>在script標(biāo)簽中通過(guò)th:inline="javascript"來(lái)聲明這是要特殊處理的js腳本
語(yǔ)法結(jié)構(gòu):
const user = /*[[Thymeleaf表達(dá)式]]*/ "靜態(tài)環(huán)境下的默認(rèn)值";
因?yàn)門hymeleaf被注釋起來(lái),因此即便是靜態(tài)環(huán)境下, js代碼也不會(huì)報(bào)錯(cuò),而是采用表達(dá)式后面跟著的默認(rèn)值。
看看頁(yè)面的源碼:

我們的User對(duì)象被直接處理為json格式了,非常方便。
控制臺(tái):


pom.xml依賴
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zhf</groupId>
<artifactId>demoboot4_01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demoboot4_01</name>
<description>demoboot4_01</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.7.RELEASE</spring-boot.version>
</properties>
<dependencies>
<!--熱部署依賴插件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.7.RELEASE</version>
<configuration>
<mainClass>com.zhf.demoboot4_01.Demoboot401Application</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>配置文件application.properties
# 應(yīng)用名稱 spring.application.name=demoboot4_01 # THYMELEAF (ThymeleafAutoConfiguration) # 開啟模板緩存(默認(rèn)值: true , 一般改為false,要不頁(yè)面可能會(huì)不實(shí)時(shí)刷新) spring.thymeleaf.cache=false # 檢查模板是否存在,然后再呈現(xiàn) spring.thymeleaf.check-template=true # 檢查模板位置是否正確(默認(rèn)值 :true ) spring.thymeleaf.check-template-location=true #Content-Type 的值(默認(rèn)值: text/html ) spring.thymeleaf.content-type=text/html # 開啟 MVC Thymeleaf 視圖解析(默認(rèn)值: true ) spring.thymeleaf.enabled=true # 模板編碼 spring.thymeleaf.encoding=UTF-8 # 要被排除在解析之外的視圖名稱列表,?逗號(hào)分隔 spring.thymeleaf.excluded-view-names= # 要運(yùn)?于模板之上的模板模式。另? StandardTemplate-ModeHandlers( 默認(rèn)值: HTML5) spring.thymeleaf.mode=HTML5 # 在構(gòu)建 URL 時(shí)添加到視圖名稱前的前綴(默認(rèn)值: classpath:/templates/ ) spring.thymeleaf.prefix=classpath:/templates/ # 在構(gòu)建 URL 時(shí)添加到視圖名稱后的后綴(默認(rèn)值: .html ) spring.thymeleaf.suffix=.html # 應(yīng)用服務(wù) WEB 訪問(wèn)端口 server.port=8080 mybatis.mapper-locations=classpath:mapperxml/*xml mybatis.type-aliases-package=com.zhf.demoboot4_01.domain # 數(shù)據(jù)庫(kù)驅(qū)動(dòng): spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # 數(shù)據(jù)源名稱 #spring.datasource.name=defaultDataSource # 數(shù)據(jù)庫(kù)連接地址 spring.datasource.url=jdbc:mysql://localhost:3306/roadhelp?serverTimezone=UTC # 數(shù)據(jù)庫(kù)用戶名&密碼: spring.datasource.username=root spring.datasource.password=root
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java調(diào)用IK分詞器進(jìn)行分詞方式,封裝工具類
這篇文章主要介紹了Java調(diào)用IK分詞器進(jìn)行分詞方式,封裝工具類,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08
idea在工具欄中顯示快速創(chuàng)建包和類的圖標(biāo)的詳細(xì)步驟
點(diǎn)擊需要?jiǎng)?chuàng)建包或者類的位置,在點(diǎn)擊對(duì)用的圖標(biāo)就可以快速創(chuàng)建類或者包了,下面小編給大家介紹idea在工具欄中顯示快速創(chuàng)建包和類的圖標(biāo)的詳細(xì)步驟,感興趣的朋友一起看看吧2024-02-02
java不用循環(huán)語(yǔ)句打印數(shù)組元素的實(shí)例
下面小編就為大家?guī)?lái)一篇java不用循環(huán)語(yǔ)句打印數(shù)組元素的實(shí)例。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-03-03
Java實(shí)現(xiàn)每日給女友微信發(fā)送早安信息
這篇文章主要為大家詳細(xì)介紹了Java如何實(shí)現(xiàn)每日給女友微信發(fā)送早安等微信信息,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,需要的可以了解一下2022-12-12
簡(jiǎn)單了解Java多態(tài)向上轉(zhuǎn)型相關(guān)原理
這篇文章主要介紹了簡(jiǎn)單了解Java多態(tài)向上轉(zhuǎn)型相關(guān)原理,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12

