知識庫 / Spring / Spring MVC RSS 訂閱

Thymeleaf 中使用布爾值

Spring MVC
HongKong
4
02:04 PM · Dec 06 ,2025

1. 簡介

在本快速教程中,我們將探討如何在 Thymeleaf 中使用布爾值。

在深入瞭解細節之前,Thymeleaf 的基本知識可以在這篇文檔中找到。

2. 評估表達式為布爾值

在 Thymeleaf 中,任何值都可以評估為布爾值。 我們有幾個值被解釋為 false

  • null
  • 布爾值 false
  • 數字 0
  • 字符 0
  • 字符串 “false”, “off”“no”

任何其他值都會被評估為 true

3. 使用布爾值作為渲染條件

要條件渲染 HTML 元素,我們有以下兩個選項:<em th:if>&nbsp;</em><em th:unless>&nbsp;</em> 屬性。

它們的效應正好相反 – Thymeleaf 如果 <em th:if> 屬性的值為 <em true&nbsp;</em>,則會渲染一個元素;如果 <em th:unless> 屬性的值為 <em false&nbsp;</em>,則會渲染一個元素。

<span th:if="${true}">will be rendered</span>
<span th:unless="${true}">won't be rendered</span>
<span th:if="${false}">won't be rendered</span>
<span th:unless="${false}">will be rendered</span>

4. 邏輯和條件運算符

此外,我們還可以使用 Thymeleaf 中的三個經典邏輯運算符:

  • and
  • or
  • 否定,使用關鍵字 not  或 “!” 符號

我們可以將這些運算符放在變量表達式內部,或使用它們組合多個變量表達式:

<span th:if="${isRaining or isCold}">The weather is bad</span>
<span th:if="${isRaining} or ${isCold}">The weather is bad</span>
<span th:if="${isSunny and isWarm}">The weather is good</span>
<span th:if="${isSunny} and ${isWarm}">The weather is good</span>
<span th:if="${not isCold}">It's warm</span>
<span th:if="${!isCold}">It's warm</span>
<span th:if="not ${isCold}">It's warm</span>
<span th:if="!${isCold}">It's warm</span>

我們還可以使用條件運算符:if-thenif-then-else 以及默認運算符。

if-then-else 運算符通常是三元運算符,也稱為 ?: 運算符。

It's <span th:text="${isCold} ? 'cold' : 'warm'"></span>

此外,if-then 運算符是簡化版本,它不包含 else 部分:

<span th:text="${isRaining or isCold} ? 'The weather is bad'"></span>

默認運算符如果第一個操作數不是 null 則返回第一個操作數,否則返回第二個操作數:

<span th:text="'foo' ?: 'bar'"></span> <!-- foo -->
<span th:text="null ?: 'bar'"></span> <!-- bar -->
<span th:text="0 ?: 'bar'"></span> <!-- 0 -->
<span th:text="1 ?: 'bar'"></span> <!-- 1 -->

默認運算符也稱為“埃爾維斯運算符”,因為它酷似埃爾維斯·普雷斯(Elvis Presley)的髮型。

請注意,埃爾維斯運算符僅進行空值檢查,它不會將第一個操作數作為布爾值進行評估。

5. #bools Utility Object

The #bools is a utility object which is available in expressions by default and has some handy methods:

  • #bools.isTrue(obj) returns whether the argument is evaluated to true
  • #bools.isFalse(obj) returns whether the argument is evaluated to false
  • #bools.xxxIsTrue(collection) converts the elements of the argument to booleans with #bools.isTrue() then collects them to the same type of collection
  • #bools.xxxIsFalse(collection) converts the elements of the argument to booleans with #bools.isFalse() then collects them to the same type of collection
  • #bools.xxxAnd(collection) returns true if all elements in the argument is evaluated to true
  • #bools.xxxOr(collection) returns true if any element in the argument is evaluated to true

In the methods above xxx can be either array, list or set, depending on the method’s argument (and return value in case of xxxIsTrue() and xxxIsFalse()).

6. 結論

在本文中,我們瞭解到Thymeleaf如何解釋布爾值,以及我們如何根據條件渲染元素並使用布爾表達式。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.