【问题标题】:Thymeleaf: check if a variable is definedThymeleaf:检查是否定义了变量
【发布时间】:2015-05-01 05:54:31
【问题描述】:

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

在 Javascript 中是这样的:

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

或者 PHP 中的这个:

if (isset($var)) { }

Thymeleaf 中是否有等价物?

【问题讨论】:

    标签: java spring spring-mvc spring-boot thymeleaf


    【解决方案1】:

    是的,您可以使用以下代码轻松检查文档是否存在给定属性。请注意,如果满足条件,您将创建 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>`
    

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

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

    【讨论】:

    • 更短的例子是完美的!
    【解决方案2】:

    短格式:

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

    【讨论】:

    • 对于对象,可以像这样使用if。如果variableinteger 的值为0,则thymeleaf 将其视为null 并且不输入de if 代码。
    【解决方案3】:

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

    百里香叶 2

    使用#vars对象的containsKey方法:

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

    百里香叶 3

    使用#ctx对象的containsVariable方法:

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 2010-09-22
        • 2021-04-21
        • 2021-10-03
        • 2012-01-20
        • 2017-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多