Thymeleaf: check if a variable is defined

后端 未结 4 1680
不思量自难忘°
不思量自难忘° 2020-12-24 05:45

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

Something like this in Javascript:

if (typeof variable !== \         


        
相关标签:
4条回答
  • 2020-12-24 06:34

    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>
    
    0 讨论(0)
  • 2020-12-24 06:34

    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.

    Thymeleaf 2

    Use the #vars object's containsKey method:

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

    Thymeleaf 3

    Use the #ctx object's containsVariable method:

    <div th:if="${#ctx.containsVariable('myVariable')}" th:text="Yes, $myVariable exists!"></div>
    
    0 讨论(0)
  • 2020-12-24 06:47

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

    <p th:text="${variable}?:''"></p>
    
    0 讨论(0)
  • 2020-12-24 06:48

    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>
    

    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>
    

    Or even shorter, without using if statement

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

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

    You can learn more about conditionals in thymeleaf here

    0 讨论(0)
提交回复
热议问题