Thymeleaf:检查是否定义了变量

And*_*rea 27 java spring spring-mvc thymeleaf spring-boot

我如何检查是否变量定义Thymeleaf

在Javascript中有类似的东西:

if (typeof variable !== 'undefined') { }
Run Code Online (Sandbox Code Playgroud)

或者这在PHP中:

if (isset($var)) { }
Run Code Online (Sandbox Code Playgroud)

在Thymeleaf中有相同的东西吗?

Try*_*usz 56

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

variable

如果你想使用div's字段,那么这个字段是否存在也值得检查

variable

甚至更短,不使用if语句

variable.name

但是,使用这种说法你会最终创建div标签是否variable还是div存在

您可以在这里了解更多关于百里香的条件


Lay*_*ros 10

简写:

<div th:if="${currentUser}">
    <h3>Name:</h3><h3 th:text="${currentUser.id}"></h3>
    <h3>Name:</h3><h3 th:text="${currentUser.username}"></h3>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 对于对象,可以像这样使用 `if`。如果 `variable` 是值为 `0` 的 `integer`,thymeleaf 会将其视为 `null`,并且不会输入 de `if` 代码。 (2认同)

小智 6

为了判断上下文是否包含给定变量,您可以直接询问上下文变量映射。这样一来,就可以确定是否完全指定了变量,这与仅定义了变量但其值为null的情况相反。

Thymeleaf 2

使用#vars对象的containsKey方法:

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

胸腺三

使用#ctx对象的containsVariable方法:

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