Thymeleaf中的比较和等式运算符介绍

x33g5p2x  于2022-09-23 转载在 其他  
字(1.7k)|赞(0)|评价(0)|浏览(541)

尽管我们不太关注这些操作,但比较器和等式运算符是 thymeleaf 表达式中的关键部分。在这篇文章中,我们将了解如何使用这些运算符。

Thymeleaf比较运算符(比较器)

您可以使用 >、 <、 >= 和 <= 比较器来比较值和表达式。这些运算符的行为方式与它们在大多数编程语言中的行为方式相同。

<button th:if="${cart.total} > 0">Checkout</button>

您还可以在表达式中使用运算符。但是,它们现在将由 SpEL 或 ONGL 进行评估。

<button th:if="${cart.total > 0}">Checkout</button>

请注意,XML 和 XHTML 不允许将 >< 放置在属性中。在这些情况下,您可以使用 HTML entities 或它们的等效文本,例如 lt (<),gt (>),le (<=),ge (>= )。考虑到这一点,下面将产生类似的输出。

<button th:if="${cart.total &gt; 0}">Checkout</button>
<button th:if="${cart.total gt 0}">Checkout</button>

Thymeleaf对象比较器

thymeleaf 中的比较器不仅适用于原始数据类型。您甚至可以比较 thymeleaf 中的 String 对象。

<button th:if="'Hello' < 'Howdy'">This will be displayed</button>
<button th:if="'Hello' > 'Howdy'">This will not be displayed</button>

在底层,Thymeleaf 使用来自 Comparable 接口的 String.compareTo() 方法。也就是说,如果它们是 Comparable,您可以比较任何两个相同类型的对象。

<button th:if="${father} > ${son}">This is possible</button>

如果对象没有实现 Comparable,那么您将收到以下错误或类似错误。

org.thymeleaf.exceptions.TemplateProcessingException:无法从表达式“${father} > ${son}”执行 GREATER THAN。

此异常是由于 thymeleaf 比较运算符的工作方式造成的。

Thymeleaf等式运算符

有时,表达式可能需要评估变量和值是否相等和不相等。这些操作是 ==!=。以下是示例。

<!--  Examples for equality  -->
<a th:if="${role} == 'ADMIN'">Admin Console</a>
<a th:if="${role} eq 'ADMIN'">Admin Console</a>
<!--  Examples for inequality  -->
<a th:if="${status} != 'LOGGEDIN'">Login</a>
<a th:if="${status} ne 'LOGGEDIN'">Login</a>
<a th:if="${status} neq 'LOGGEDIN'">Login</a>

正如您在上面的示例中看到的,等式运算符也有文本别名,如eq (==)neq/ne (!=)

结论

总而言之,我们通过几个例子了解了 thymeleaf 中的比较和等式运算符。如果您想查看它们的实际效果,请查看 thymeleaf CRUD 示例。

相关文章