【发布时间】:2015-05-01 05:54:31
【问题描述】:
如何检查 Thymeleaf 中是否定义了变量?
在 Javascript 中是这样的:
if (typeof variable !== 'undefined') { }
或者 PHP 中的这个:
if (isset($var)) { }
Thymeleaf 中是否有等价物?
【问题讨论】:
标签: java spring spring-mvc spring-boot thymeleaf
如何检查 Thymeleaf 中是否定义了变量?
在 Javascript 中是这样的:
if (typeof variable !== 'undefined') { }
或者 PHP 中的这个:
if (isset($var)) { }
Thymeleaf 中是否有等价物?
【问题讨论】:
标签: java spring spring-mvc spring-boot thymeleaf
是的,您可以使用以下代码轻松检查文档是否存在给定属性。请注意,如果满足条件,您将创建 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>`
但使用此语句,无论variable 或variable.name 是否存在,您都将结束创建div 标记
您可以在 thymeleaf here 中了解有关条件的更多信息
【讨论】:
短格式:
<div th:if="${currentUser}">
<h3>Name:</h3><h3 th:text="${currentUser.id}"></h3>
<h3>Name:</h3><h3 th:text="${currentUser.username}"></h3>
</div>
【讨论】:
if。如果variable 是integer 的值为0,则thymeleaf 将其视为null 并且不输入de if 代码。
为了判断上下文是否包含给定变量,可以直接询问上下文变量映射。这可以让我们确定是否完全指定了变量,而不是仅在定义变量但值为 null 的情况下。
使用#vars对象的containsKey方法:
<div th:if="${#vars.containsKey('myVariable')}" th:text="Yes, $myVariable exists!"></div>
使用#ctx对象的containsVariable方法:
<div th:if="${#ctx.containsVariable('myVariable')}" th:text="Yes, $myVariable exists!"></div>
【讨论】:
您可以使用条件运算符。如果存在或为空字符串,这将写入变量:
<p th:text="${variable}?:''"></p>
【讨论】: