Thymeleaf:检查是否定义了变量
如何检查Thymeleaf中 是否定义了变量?
Javascript中有类似的东西:
if (typeof variable !== 'undefined') { }
或者这在PHP中:
if (isset($var)) { }
在Thymeleaf中有相同的东西吗?
是的,您可以使用以下代码轻松检查文档是否存在给定属性。 请注意,如果满足条件,则创建div
标记:
I wonder, if variable exists...
如果你想使用variable
的字段,那么值得检查这个字段是否也存在
I wonder, if variable.name exists...
甚至更短,不使用if语句
I wonder, if variable.name exists...
但是使用此语句,您将结束创建div
标记,无论是variable
还是variable.name
.name存在
您可以在这里了解更多关于百里香的条件
简写:
Name:
Name:
为了判断上下文是否包含给定变量,您可以直接询问上下文变量map。 这使得人们可以确定是否完全指定变量,而不是仅定义变量但值为null的情况。
Thymeleaf 2
使用#vars
对象的containsKey
方法:
Thymeleaf 3
使用#ctx
对象的containsVariable
方法: