Using Thymeleaf when the value is null

后端 未结 10 1770
傲寒
傲寒 2020-11-29 21:01

I have some values in my database which can be null if they have not already been entered.

But when I use Thymeleaf in my html, it gives an error when parsing null v

相关标签:
10条回答
  • 2020-11-29 21:27

    I use

    <div th:text ="${variable != null} ? (${variable != ''} ? ${variable} : 'empty string message') : 'null message' "></div>
    
    0 讨论(0)
  • 2020-11-29 21:30

    This can also be handled using the elvis operator ?: which will add a default value when the field is null:

    <span th:text="${object.property} ?: 'default value'"></span>
    
    0 讨论(0)
  • 2020-11-29 21:36

    The shortest way is using '?' operator. If you have User entity with embedded Address entity in order to access fields of Address entity and print them if address is not null, otherwise here will be an empty column:

    <td th:text="${user?.address?.city}"></td>
    
    0 讨论(0)
  • 2020-11-29 21:38

    Also worth to look at documentation for #objects build-in helper: https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#objects

    There is useful: ${#objects.nullSafe(obj, default)}

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