解讀thymeleaf模板引擎中th:if的使用
thymeleaf模板引擎中th:if的使用
th:if 條件判斷
很多時候只有在滿?某個條件時,才將?個模板?段顯示在結(jié)果中,否則不進(jìn)行顯示。比如只有當(dāng)用戶有訂單時,才為它顯示訂單鏈接,否則不顯示。th:if 屬性用于滿足這個需求
<body> <!--if屬性結(jié)果為 true,模板會進(jìn)行顯示--> <p th:if="true">th:if="true"</p> <!--if屬性結(jié)果為 false,模板不會進(jìn)行顯示--> <p th:if="false">th:if="false"</p> <!--后臺控制器傳出數(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 時,判斷為 false;不為零時,判定為 true
- 如果值是是 String,值為 “false”、“off”、“no” 時,判定為 false,否則判斷為 true,字符串為空時,也判斷為 true
- 如果值不是布爾值,數(shù)字,字符或字符串的其它對象,只要不為 null,則判斷為 true
<body> <!--表達(dá)式的結(jié)果為布爾類型時,if 直接以它為結(jié)果--> <p th:if="true">th:if="true"</p> <!--當(dāng)表達(dá)式結(jié)果為null時,則if判定為false--> <p th:if="null">th:if="null"</p> <!--表達(dá)式為數(shù)字時,不為0,if判定為true,為0,時,if判定為false--> <p th:if="11">th:if="11"</p> <p th:if="0">th:if="0"</p> <!--表達(dá)式結(jié)果為字符串時,如果為 true,則if判定為true;值為 false,則if判定為false--> <!--結(jié)果為 off、no 等特殊字符串時,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時,if判定為true--> <p th:if="'Love China'">th:if="'Love China'"</p> <!--后臺傳輸:model.addAttribute("userList", User.getUsers());--> <!--只要 userList 不等于null,則if判定為true,否則為false--> <p th:if="${userList}">th:if="${userList}"</p> <!--后臺傳輸:model.addAttribute("name", "");--> <!--字符串為空時,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模板引擎語法使用
1、模板引擎thymeleaf使用
引入依賴:
<dependency>? ? ? <groupId>org.springframework.boot</groupId>? ? ? <artifactId>spring-boot-starter-thymeleaf</artifactId>? </dependency>
頁面導(dǎo)入頭部文件:
<html xmlns:th="http://www.thymeleaf.org">
語法說明:
Thymeleaf通過 ${}來獲取model中的變量,注意這不是el 表達(dá)式,而是ognl表達(dá)式,但是語法非常像。
2、ognl表達(dá)式的語法糖
剛才獲取變量值,我們使用的是經(jīng)典的對象.屬性名方式。但有些情況下,我們的屬性名可能本身也是變量,怎么辦?
ognl提供了類似js的語法方式:
例如:${user.name} 可以寫作${user['name']}
自定義變量
場景
看下面的案例:
<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ù)量比較多的時候,頻繁的寫user.就會非常麻煩。
因此,Thymeleaf提供了自定義變量來解決:
示例:
<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)部的任意元素上,可以通過 *{屬性名}的方式,來獲取user中的屬性,這樣就省去了大量的user.前綴了
3、拼接
我們經(jīng)常會用到普通字符串與表達(dá)式拼接的情況:
<span th:text="'歡迎您:' + ${user.name} + '!'"></span>
字符串字面值需要用'',拼接起來非常麻煩,Thymeleaf對此進(jìn)行了簡化,使用一對|即可:
<span th:text="|歡迎您:${user.name}|"></span>
與上面是完全等效的,這樣就省去了字符串字面值的書寫。
4、運算
需要注意:${}內(nèi)部的是通過OGNL表達(dá)式引擎解析的,外部的才是通過Thymeleaf的引擎解析,因此運算符盡量放在${}外進(jìn)行。
算術(shù)運算
支持的算術(shù)運算符:+ - * / %
<span th:text="${user.age}"></span> <span th:text="${user.age}%2 == 0"></span>
比較運算
支持的比較運算:>, <, >= and <= ,但是>, <不能直接使用,因為xml會解析為標(biāo)簽,要使用別名。
注意 == and !=不僅可以比較數(shù)值,類似于equals的功能。
可以使用的別名:gt (>), lt (<), ge (>=), le (<=), not (!). Also eq (==), neq/ne (!=).
條件運算
三元運算
<span th:text="${user.sex} ? '男':'女'"></span>
三元運算符的三個部分:conditon ? then : else
- ?
condition
:條件 - ?
then
:條件成立的結(jié)果 - ?
else
:不成立的結(jié)果
其中的每一個部分都可以是Thymeleaf中的任意表達(dá)式。
默認(rèn)值
有的時候,我們?nèi)∫粋€值可能為空,這個時候需要做非空判斷,可以使用 表達(dá)式 ?: 默認(rèn)值簡寫:
<span th:text="${user.name} ?: '二狗'"></span>
當(dāng)前面的表達(dá)式值為null時,就會使用后面的默認(rèn)值。
注意:?:之間沒有空格。
5、循環(huán)
循環(huán)也是非常頻繁使用的需求,我們使用th:each指令來完成:
假如有用戶的集合: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
,實現(xiàn)了Iterable接口的類Enumeration
,枚舉Interator
,迭代器Map
,遍歷得到的是Map.EntryArray
,數(shù)組及其它一切符合數(shù)組結(jié)果的對象
在迭代的同時,我們也可以獲取迭代的狀態(tài)對象:
<tr th:each="user,stat : ${users}"> <td th:text="${user.name}">Onions</td> <td th:text="${user.age}">2.41</td> </tr>
stat對象包含以下屬性:
index
,從0開始的角標(biāo)count
,元素的個數(shù),從1開始size
,總元素個數(shù)current
,當(dāng)前遍歷到的元素even
/odd
,返回是否為奇偶,boolean值first
/last
,返回是否為第一或最后,boolean值
6、邏輯判斷
有了if和else,我們能實現(xiàn)一切功能_。
Thymeleaf中使用th:if 或者 th:unless ,兩者的意思恰好相反
<span th:if="${user.age} < 24">小鮮肉</span>
如果表達(dá)式的值為true,則標(biāo)簽會渲染到頁面,否則不進(jìn)行渲染。
以下情況被認(rèn)定為true:
- 表達(dá)式值為true
- 表達(dá)式值為非0數(shù)值
- 表達(dá)式值為非0字符
- 表達(dá)式值為字符串,但不是"false","no","off"
- 表達(dá)式不是布爾、字符串、數(shù)字、字符中的任何一種
其它情況包括null都被認(rèn)定為false
7、分支控制switch
這里要使用兩個指令: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>
需要注意的是,一旦有一個th:case成立,其它的則不再判斷。與java中的switch是一樣的。
另外th:case="*"表示默認(rèn),放最后
頁面
8、JS模板
模板引擎不僅可以渲染html,也可以對JS中的進(jìn)行預(yù)處理。而且為了在純靜態(tài)環(huán)境下可以運行,其Thymeleaf代碼可以被注釋起來:
<script th:inline="javascript"> const user = /*[[${user}]]*/ {}; const age = /*[[${user.age}]]*/ 20; console.log(user); console.log(age) </script>
在script標(biāo)簽中通過th:inline="javascript"來聲明這是要特殊處理的js腳本
語法結(jié)構(gòu):
const user = /*[[Thymeleaf表達(dá)式]]*/ "靜態(tài)環(huán)境下的默認(rèn)值";
因為Thymeleaf被注釋起來,因此即便是靜態(tài)環(huán)境下, js代碼也不會報錯,而是采用表達(dá)式后面跟著的默認(rèn)值。
看看頁面的源碼:
我們的User對象被直接處理為json格式了,非常方便。
控制臺:
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,要不頁面可能會不實時刷新) 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 # 要被排除在解析之外的視圖名稱列表,?逗號分隔 spring.thymeleaf.excluded-view-names= # 要運?于模板之上的模板模式。另? StandardTemplate-ModeHandlers( 默認(rèn)值: HTML5) spring.thymeleaf.mode=HTML5 # 在構(gòu)建 URL 時添加到視圖名稱前的前綴(默認(rèn)值: classpath:/templates/ ) spring.thymeleaf.prefix=classpath:/templates/ # 在構(gòu)建 URL 時添加到視圖名稱后的后綴(默認(rèn)值: .html ) spring.thymeleaf.suffix=.html # 應(yīng)用服務(wù) WEB 訪問端口 server.port=8080 mybatis.mapper-locations=classpath:mapperxml/*xml mybatis.type-aliases-package=com.zhf.demoboot4_01.domain # 數(shù)據(jù)庫驅(qū)動: spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # 數(shù)據(jù)源名稱 #spring.datasource.name=defaultDataSource # 數(shù)據(jù)庫連接地址 spring.datasource.url=jdbc:mysql://localhost:3306/roadhelp?serverTimezone=UTC # 數(shù)據(jù)庫用戶名&密碼: spring.datasource.username=root spring.datasource.password=root
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
java數(shù)據(jù)結(jié)構(gòu)之希爾排序
這篇文章主要為大家詳細(xì)介紹了java數(shù)據(jù)結(jié)構(gòu)之希爾排序的相關(guān)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11Java中ByteBuffer的allocate方法 和allocateDirect方法的區(qū)別和選用原則解析
在Java中,ByteBuffer是java.nio包中的一個類,用于處理字節(jié)數(shù)據(jù),ByteBuffer提供了兩種方式來分配內(nèi)存:allocate和allocateDirect,這篇文章主要介紹了Java中ByteBuffer的allocate方法 和allocateDirect方法的區(qū)別和選用原則 ,需要的朋友可以參考下2023-12-12Java中ClassLoader類加載學(xué)習(xí)總結(jié)
本篇文章主要給大家講述了Java中ClassLoader類加載的原理以及用法總結(jié),一起學(xué)習(xí)下。2017-12-12SpringBoot修改內(nèi)置tomcat版本的操作步驟
生產(chǎn)環(huán)境使用的外部部署Tomcat還是內(nèi)置Tomcat由于版本安全漏洞,往往需要升級到指定的安全版本,本文演示一下SpringBoot升級內(nèi)置的Tomcat版本,感興趣的小伙伴跟著小編一起來看看吧2024-07-07SpringBoot?整合MyBatis+MyBatis-Plus+MyBatisX插件使用
本文主要介紹了SpringBoot?整合MyBatis+MyBatis-Plus+MyBatisX插件使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-04-04Intellij IDEA導(dǎo)入eclipse web項目的操作步驟詳解
Eclipse當(dāng)中的web項目都會有這兩個文件,但是idea當(dāng)中應(yīng)該是沒有的,所以導(dǎo)入會出現(xiàn)兼容問題,但是本篇文章會教大家如何導(dǎo)入,并且導(dǎo)入過后還能使用tomcat運行,需要的朋友可以參考下2023-08-08Springboot+Thymeleaf+Jpa實現(xiàn)登錄功能(附源碼)
最近有學(xué)習(xí)到關(guān)于Springboot+Thymeleaf+Jpa的綜合運用知識,因此想寫一個簡單的登錄界面來嘗試一下,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05Springboot整合Druid實現(xiàn)對訪問的監(jiān)控方式
這篇文章主要介紹了Springboot整合Druid實現(xiàn)對訪問的監(jiān)控方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05Java基于ReadWriteLock實現(xiàn)鎖的應(yīng)用
這篇文章主要介紹了Java基于ReadWriteLock實現(xiàn)鎖的應(yīng)用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-10-10