Thymeleaf:检查变量是否已定义

问题描述 投票:0回答:4

如何检查 Thymeleaf 中是否定义了变量

Javascript 中类似这样的东西:

if (typeof variable !== 'undefined') { }

或者 PHP 中的这个:

if (isset($var)) { }

Thymeleaf 中有等效的吗?

java spring spring-mvc spring-boot thymeleaf
4个回答
77
投票
是的,您可以使用以下代码轻松检查文档是否存在给定属性。请注意,如果满足条件,您将创建一个

div

 标签:

<div th:if="${variable != null}" th:text="Yes, variable exists!"> I wonder, if variable exists... </div>
如果您想使用 

variable

 的字段,值得检查该字段是否也存在

<div th:if="${variable != null && variable.name != null}" th:text="${variable.name}"> I wonder, if variable.name exists... </div>
甚至更短,不使用 if 语句

<div th:text="${variable?.name}"> I wonder, if variable.name exists... </div>`
但是使用此语句,无论 

div

variable
 是否存在
,您都将结束创建
variable.name
标签

您可以在这里

了解有关 thymeleaf 中条件语句的更多信息


16
投票
简称:

<div th:if="${currentUser}"> <h3>Name:</h3><h3 th:text="${currentUser.id}"></h3> <h3>Name:</h3><h3 th:text="${currentUser.username}"></h3> </div>
    

11
投票
为了判断上下文是否包含给定变量,可以直接询问上下文变量映射。这可以让我们确定变量是否被指定,而不是仅定义变量但值为 null。

百里香叶2

使用

#vars

 对象的 containsKey
 方法:

<div th:if="${#vars.containsKey('myVariable')}" th:text="Yes, $myVariable exists!"></div>

百里香叶3

使用

#ctx

 对象的 containsVariable
 方法:

<div th:if="${#ctx.containsVariable('myVariable')}" th:text="Yes, $myVariable exists!"></div>
    

1
投票
您可以使用条件运算符。如果存在或空字符串,这将写入变量:

<p th:text="${variable}?:''"></p>
    
© www.soinside.com 2019 - 2024. All rights reserved.