解讀thymeleaf模板引擎中th:if的使用
thymeleaf模板引擎中th:if的使用
th:if 條件判斷
很多時候只有在滿?某個條件時,才將?個模板?段顯示在結果中,否則不進行顯示。比如只有當用戶有訂單時,才為它顯示訂單鏈接,否則不顯示。th:if 屬性用于滿足這個需求
<body>
<!--if屬性結果為 true,模板會進行顯示-->
<p th:if="true">th:if="true"</p>
<!--if屬性結果為 false,模板不會進行顯示-->
<p th:if="false">th:if="false"</p>
<!--后臺控制器傳出數據:model.addAttribute("isMarry", true);-->
<p th:if="${isMarry}">已婚</p>
</body>th:if 屬性不僅只以布爾值作為判斷條件,它將按照如下規(guī)則判定指定的表達式結果為 true:
- 如果表達式結果為布爾值,則為 true 或 false
- 如果表達式的值為 null,th:if 將判定此表達式為 false
- 如果值是數字,為 0 時,判斷為 false;不為零時,判定為 true
- 如果值是是 String,值為 “false”、“off”、“no” 時,判定為 false,否則判斷為 true,字符串為空時,也判斷為 true
- 如果值不是布爾值,數字,字符或字符串的其它對象,只要不為 null,則判斷為 true
<body>
<!--表達式的結果為布爾類型時,if 直接以它為結果-->
<p th:if="true">th:if="true"</p>
<!--當表達式結果為null時,則if判定為false-->
<p th:if="null">th:if="null"</p>
<!--表達式為數字時,不為0,if判定為true,為0,時,if判定為false-->
<p th:if="11">th:if="11"</p>
<p th:if="0">th:if="0"</p>
<!--表達式結果為字符串時,如果為 true,則if判定為true;值為 false,則if判定為false-->
<!--結果為 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>
<!--表達式結果字符串不為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 判斷表達式
gt:(大于)>ge:(大于等于)>=eq:(等于)==lt:(小于)<le:(小于等于)<=ne:(不等于)!=
Thymeleaf模板引擎語法使用
1、模板引擎thymeleaf使用
引入依賴:
<dependency>? ? ? <groupId>org.springframework.boot</groupId>? ? ? <artifactId>spring-boot-starter-thymeleaf</artifactId>? </dependency>
頁面導入頭部文件:
<html xmlns:th="http://www.thymeleaf.org">
語法說明:
Thymeleaf通過 ${}來獲取model中的變量,注意這不是el 表達式,而是ognl表達式,但是語法非常像。
2、ognl表達式的語法糖
剛才獲取變量值,我們使用的是經典的對象.屬性名方式。但有些情況下,我們的屬性名可能本身也是變量,怎么辦?
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>我們獲取用戶的所有信息,分別展示。
當數據量比較多的時候,頻繁的寫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內部的任意元素上,可以通過 *{屬性名}的方式,來獲取user中的屬性,這樣就省去了大量的user.前綴了
3、拼接
我們經常會用到普通字符串與表達式拼接的情況:
<span th:text="'歡迎您:' + ${user.name} + '!'"></span>字符串字面值需要用'',拼接起來非常麻煩,Thymeleaf對此進行了簡化,使用一對|即可:
<span th:text="|歡迎您:${user.name}|"></span>與上面是完全等效的,這樣就省去了字符串字面值的書寫。

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

默認值
有的時候,我們取一個值可能為空,這個時候需要做非空判斷,可以使用 表達式 ?: 默認值簡寫:
<span th:text="${user.name} ?: '二狗'"></span>當前面的表達式值為null時,就會使用后面的默認值。
注意:?:之間沒有空格。

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,實現了Iterable接口的類Enumeration,枚舉Interator,迭代器Map,遍歷得到的是Map.EntryArray,數組及其它一切符合數組結果的對象
在迭代的同時,我們也可以獲取迭代的狀態(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開始的角標count,元素的個數,從1開始size,總元素個數current,當前遍歷到的元素even/odd,返回是否為奇偶,boolean值first/last,返回是否為第一或最后,boolean值
6、邏輯判斷
有了if和else,我們能實現一切功能_。
Thymeleaf中使用th:if 或者 th:unless ,兩者的意思恰好相反
<span th:if="${user.age} < 24">小鮮肉</span>如果表達式的值為true,則標簽會渲染到頁面,否則不進行渲染。
以下情況被認定為true:
- 表達式值為true
- 表達式值為非0數值
- 表達式值為非0字符
- 表達式值為字符串,但不是"false","no","off"
- 表達式不是布爾、字符串、數字、字符中的任何一種
其它情況包括null都被認定為false

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

頁面

8、JS模板
模板引擎不僅可以渲染html,也可以對JS中的進行預處理。而且為了在純靜態(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標簽中通過th:inline="javascript"來聲明這是要特殊處理的js腳本
語法結構:
const user = /*[[Thymeleaf表達式]]*/ "靜態(tài)環(huán)境下的默認值";
因為Thymeleaf被注釋起來,因此即便是靜態(tài)環(huán)境下, js代碼也不會報錯,而是采用表達式后面跟著的默認值。
看看頁面的源碼:

我們的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
# 應用名稱 spring.application.name=demoboot4_01 # THYMELEAF (ThymeleafAutoConfiguration) # 開啟模板緩存(默認值: true , 一般改為false,要不頁面可能會不實時刷新) spring.thymeleaf.cache=false # 檢查模板是否存在,然后再呈現 spring.thymeleaf.check-template=true # 檢查模板位置是否正確(默認值 :true ) spring.thymeleaf.check-template-location=true #Content-Type 的值(默認值: text/html ) spring.thymeleaf.content-type=text/html # 開啟 MVC Thymeleaf 視圖解析(默認值: true ) spring.thymeleaf.enabled=true # 模板編碼 spring.thymeleaf.encoding=UTF-8 # 要被排除在解析之外的視圖名稱列表,?逗號分隔 spring.thymeleaf.excluded-view-names= # 要運?于模板之上的模板模式。另? StandardTemplate-ModeHandlers( 默認值: HTML5) spring.thymeleaf.mode=HTML5 # 在構建 URL 時添加到視圖名稱前的前綴(默認值: classpath:/templates/ ) spring.thymeleaf.prefix=classpath:/templates/ # 在構建 URL 時添加到視圖名稱后的后綴(默認值: .html ) spring.thymeleaf.suffix=.html # 應用服務 WEB 訪問端口 server.port=8080 mybatis.mapper-locations=classpath:mapperxml/*xml mybatis.type-aliases-package=com.zhf.demoboot4_01.domain # 數據庫驅動: spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # 數據源名稱 #spring.datasource.name=defaultDataSource # 數據庫連接地址 spring.datasource.url=jdbc:mysql://localhost:3306/roadhelp?serverTimezone=UTC # 數據庫用戶名&密碼: spring.datasource.username=root spring.datasource.password=root
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Java中ByteBuffer的allocate方法 和allocateDirect方法的區(qū)別和選用原則解析
在Java中,ByteBuffer是java.nio包中的一個類,用于處理字節(jié)數據,ByteBuffer提供了兩種方式來分配內存:allocate和allocateDirect,這篇文章主要介紹了Java中ByteBuffer的allocate方法 和allocateDirect方法的區(qū)別和選用原則 ,需要的朋友可以參考下2023-12-12
SpringBoot?整合MyBatis+MyBatis-Plus+MyBatisX插件使用
本文主要介紹了SpringBoot?整合MyBatis+MyBatis-Plus+MyBatisX插件使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-04-04
Intellij IDEA導入eclipse web項目的操作步驟詳解
Eclipse當中的web項目都會有這兩個文件,但是idea當中應該是沒有的,所以導入會出現兼容問題,但是本篇文章會教大家如何導入,并且導入過后還能使用tomcat運行,需要的朋友可以參考下2023-08-08
Springboot+Thymeleaf+Jpa實現登錄功能(附源碼)
最近有學習到關于Springboot+Thymeleaf+Jpa的綜合運用知識,因此想寫一個簡單的登錄界面來嘗試一下,需要的朋友們下面隨著小編來一起學習學習吧2021-05-05
Springboot整合Druid實現對訪問的監(jiān)控方式
這篇文章主要介紹了Springboot整合Druid實現對訪問的監(jiān)控方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05

