Thymeleaf:检查是否定义了变量 [英] Thymeleaf: check if a variable is defined

查看:477
本文介绍了Thymeleaf:检查是否定义了变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I check if a variable is defined in Thymeleaf?

在Javascript中是这样的:

Something like this in Javascript:

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

或者在PHP中这样:

if (isset($var)) { }

胸腺有等同体吗?

推荐答案

是的,您可以使用以下代码轻松检查文档的给定属性是否存在.请注意,如果满足条件,您将创建div标记:

Yes, you can easily check if given property exists for your document using following code. Note, that you're creating div tag if condition is met:

<div th:if="${variable != null}" th:text="Yes, variable exists!">
   I wonder, if variable exists...
</div>

如果您想使用variable的字段,则值得检查此字段是否也存在

If you want using variable's field it's worth checking if this field exists as well

<div th:if="${variable != null && variable.name != null}" th:text="${variable.name}">
   I wonder, if variable.name exists...
</div>

甚至更短,无需使用if语句

Or even shorter, without using if statement

<div th:text="${variable?.name}">
   I wonder, if variable.name exists...
</div>`

但是使用此语句,无论variable还是variable.name存在,您都将结束创建div标记

But using this statement you will end creating div tag whether variable or variable.name exist

您可以在百里香 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆