Thymeleaf:如果属性和属性存在,则显示文本 [英] Thymeleaf: show text if the attribute and property exists
问题描述
如果属性和属性存在,百里香中是否有一种简单的方法可以显示属性的内容?如果我的html页面中有一个属性错误"和一个属性摘要",我想显示它:
Is there a simple way in thymeleaf to show the content of an attribute property if the property and the attribute exist? If there's an attribute "error" with a property "summary" in my html page, I'd like to show it:
<span th:text="${error.summary}">error summary</span>
如果没有属性错误",则会引发以下错误:
If there is no attribute "error" the following error is raised:
org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Field or property 'summary' cannot be found on null
当前,我正在使用以下方法,这似乎太复杂了.
Currently I'm using the following approach, which just seems too complicated.
<span th:if="${error != null and error.summary != null}"><span th:text="${error.summary}">error summary</span></span>
有没有更简单的方法来实现这一目标?
Is there a simpler way to achieve that?
推荐答案
当然!由于与th:if
属性关联的处理器具有较高的优先级,而不是与th:text
属性相关联的那个.因此,您可以编写:
Sure! Since the processor associated with the th:if
attribute has a higher precedence than the one associated with the th:text
attribute, it will be evaluated first. Thus you can write:
<span th:if="${error != null && error.summary != null}" th:text="${error.summary}">Static summary</span>
您甚至可以使用以下方法将其缩短:
You could even shorten it using:
<span th:text="${error?.summary}">Static summary</span>
但是我认为在这种情况下,无论摘要是否存在,都会创建span标签,这有点难看.
But I think in this case, whether the summary exist or not, the span tag will be created, which is a bit ugly.
在此处中查看有关条件表达式的更多信息.
See more info about conditional expressions here.
这篇关于Thymeleaf:如果属性和属性存在,则显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!