Java Thymeleaf:检查是否定义了变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28783385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:48:06  来源:igfitidea点击:

Thymeleaf: check if a variable is defined

javaspringspring-mvcspring-bootthymeleaf

提问by Andrea

How can I check if a variable is definedin Thymeleaf?

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

Something like this in Javascript:

在 Javascript 中是这样的:

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

or this in PHP:

或在 PHP 中:

if (isset($var)) { }

Is there an equivalent in Thymeleaf?

Thymeleaf 中是否有等价物?

采纳答案by Trynkiewicz Mariusz

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

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

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

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

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

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

Or even shorter, without using if statement

甚至更短,不使用 if 语句

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

But using this statement you will end creating divtag whether variableor variable.nameexist

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

You can learn more about conditionals in thymeleaf here

您可以在此处了解有关 thymeleaf 中的条件的更多信息

回答by Lay Leangsros

Short form:

简写:

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

回答by Lay Leangsros

In order to tell whether the context contains a given variable, you can ask the context variable map directly. This lets one determine whether the variable is specified at all, as opposed to the only the cases where it's defined but with a value of null.

为了判断上下文是否包含给定变量,可以直接询问上下文变量映射。这让我们可以确定是否完全指定了变量,而不是仅在定义了变量但值为 null 的情况下。

Thymeleaf 2

百里香叶 2

Use the #varsobject's containsKeymethod:

使用#vars对象的containsKey方法:

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

Thymeleaf 3

百里香叶 3

Use the #ctxobject's containsVariablemethod:

使用#ctx对象的containsVariable方法:

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

回答by Aleksandar Nikolic

You can use conditional operators. This will write variable if exists or empty string:

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

<p th:text="${variable}?:''"></p>