1. 简介
本文将深入探讨 Thymeleaf 中布尔值的处理技巧。如果你对 Thymeleaf 基础不熟悉,建议先阅读这篇文章。
2. 布尔表达式求值
在 Thymeleaf 中,任何值都能被当作布尔值求值。以下值会被判定为 false
:
null
- 布尔值
false
- 数字
0
- 字符
'0'
- 字符串
"false"
、"off"
、"no"
其他所有值都会被判定为 true
。
3. 布尔值控制渲染
要实现条件渲染,有两种方式:th:if
和 th:unless
属性。它们的作用完全相反:
th:if
:条件为true
时渲染元素th:unless
:条件为false
时渲染元素
<span th:if="${true}">会渲染</span>
<span th:unless="${true}">不会渲染</span>
<span th:if="${false}">不会渲染</span>
<span th:unless="${false}">会渲染</span>
4. 逻辑与条件运算符
Thymeleaf 支持三种经典逻辑运算符:
and
or
- 取反:使用
not
关键字或!
符号
这些运算符可以灵活组合使用:
<span th:if="${isRaining or isCold}">天气糟糕</span>
<span th:if="${isRaining} or ${isCold}">天气糟糕</span>
<span th:if="${isSunny and isWarm}">天气不错</span>
<span th:if="${isSunny} and ${isWarm}">天气不错</span>
<span th:if="${not isCold}">天气暖和</span>
<span th:if="${!isCold}">天气暖和</span>
<span th:if="not ${isCold}">天气暖和</span>
<span th:if="!${isCold}">天气暖和</span>
还支持条件运算符:
三元运算符(if-then-else):
天气<span th:text="${isCold} ? '寒冷' : '温暖'"></span>
简化版(if-then):
<span th:text="${isRaining or isCold} ? '天气糟糕'"></span>
默认值运算符(Elvis 运算符):
<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 运算符只检查 null
,不会将第一个操作数当作布尔值求值。
5. #bools 工具对象
#bools
是内置工具对象,提供实用方法:
#bools.isTrue(obj)
:判断参数是否为true
#bools.isFalse(obj)
:判断参数是否为false
#bools.xxxIsTrue(collection)
:转换集合元素为布尔值(使用isTrue
)#bools.xxxIsFalse(collection)
:转换集合元素为布尔值(使用isFalse
)#bools.xxxAnd(collection)
:集合所有元素为true
时返回true
#bools.xxxOr(collection)
:集合任一元素为true
时返回true
其中 xxx
可替换为 array
、list
或 set
,取决于参数类型。
6. 总结
本文介绍了 Thymeleaf 如何将值解析为布尔值,以及如何进行条件渲染和布尔表达式操作。完整示例代码可在 GitHub 获取。