当值为null时使用Thymeleaf

ser*_*kan 61 html null thymeleaf

我的数据库中有一些值,如果尚未输入,则可以为null.

但是当我在我的html中使用Thymeleaf时,它在解析空值时会出错.

有办法处理这个吗?

小智 106

最短的方法是使用'?' 运营商.如果您具有嵌入地址实体的用户实体以访问地址实体的字段并在地址不为空时打印它们,否则这将是一个空列:

<td th:text="${user?.address?.city}"></td>
Run Code Online (Sandbox Code Playgroud)

  • 根据[Spring Expression Language docs],将"?."运算符称为"安全导航"运算符(https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/ expressions.html#表达式运营商安全导航). (5认同)
  • 使用 ?数值字段为 0 时也会产生 false。因此,您需要在数字字段上使用完整的 != null 条件。 (3认同)
  • 我在 SpringBoot 2.6 中收到 ognl.ExpressionSyntaxException: Malformed OGNL expression: error (3认同)
  • 虽然上面的语法在 thymeleaf 3.0.9 附带的 spring boot 2.0.5 中被接受为有效,但至少对我来说,它并没有执行此处声明的操作。这是您必须启用的特殊功能吗? (2认同)

tdu*_*eau 55

当然有.例如,您可以使用条件表达式.例如:

<span th:text="${someObject.someProperty != null} ? ${someObject.someProperty} : 'null value!'">someValue</span>
Run Code Online (Sandbox Code Playgroud)

你甚至可以省略"else"表达式:

<span th:text="${someObject.someProperty != null} ? ${someObject.someProperty}">someValue</span>
Run Code Online (Sandbox Code Playgroud)

您还可以查看Elvis运算符以显示默认值.


Rob*_*rto 12

您可以将'th:if'与'th:text'一起使用

<span th:if="${someObject.someProperty != null}" th:text="${someObject.someProperty}">someValue</span>
Run Code Online (Sandbox Code Playgroud)

  • 仅需&lt;!= null``&lt;span th:if =“ $ {someObject.someProperty}” ...`就足够了 (3认同)

Jua*_*oza 9

这也可以使用elvis运算符 来处理,该运算符?:将在字段为null时添加默认值:

<span th:text="${object.property} ?: 'default value'"></span>
Run Code Online (Sandbox Code Playgroud)

  • 这可能是在百里香中显示默认值的最优雅的方式。值得更多的支持! (3认同)

小智 8

还值得查看#objects 内置助手的文档:https ://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#objects

有一个有用的: ${#objects.nullSafe(obj, default)}


Ah *_*ang 6

您在创建时已完成两次检查

${someObject.someProperty != null} ? ${someObject.someProperty}
Run Code Online (Sandbox Code Playgroud)

你应该干净简单,如下所示.

<td th:text="${someObject.someProperty} ? ${someObject.someProperty} : 'null value!'"></td>
Run Code Online (Sandbox Code Playgroud)


Vaz*_*yan 5

   <p data-th-text ="${#strings.defaultString(yourNullable,'defaultValueIfYourValueIsNull')}"></p>
Run Code Online (Sandbox Code Playgroud)