如果属性和属性存在,百里香叶中是否有一种简单的方法来显示属性属性的内容?如果在我的html页面中存在属性“summary”的属性“error”,我想展示它:
<span th:text="${error.summary}">error summary</span>
如果没有属性“error”,则会引发以下错误:
org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Field or property 'summary' cannot be found on null
目前我正在使用以下方法,这看起来太复杂了。
<span th:if="${error != null and error.summary != null}"><span th:text="${error.summary}">error summary</span></span>
有没有更简单的方法来实现这一目标?
答案 0 :(得分:47)
当然!由于与th:if
属性关联的处理器的higher precedence与th:text
属性关联的处理器的here,因此将首先对其进行评估。因此你可以写:
<span th:if="${error != null && error.summary != null}" th:text="${error.summary}">Static summary</span>
您甚至可以使用以下方式缩短它:
<span th:text="${error?.summary}">Static summary</span>
但我认为在这种情况下,无论摘要是否存在,都会创建span标记,这有点难看。
查看有关条件表达式{{3}}的更多信息。