spring Thymeleaf:如果属性和属性存在,则显示文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21529085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 06:31:51  来源:igfitidea点击:

Thymeleaf: show text if the attribute and property exists

springthymeleafspring-el

提问by James

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:

如果属性和属性存在,thymeleaf 中是否有一种简单的方法来显示属性属性的内容?如果在我的 html 页面中有一个带有属性“摘要”的属性“错误”,我想显示它:

<span th:text="${error.summary}">error summary</span>

If there is no attribute "error" the following error is raised:

如果没有属性“error”,则会引发以下错误:

org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Field or property 'summary' cannot be found on null

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?

有没有更简单的方法来实现这一目标?

回答by tduchateau

Sure! Since the processor associated with the th:ifattribute has a higher precedencethan the one associated with the th:textattribute, it will be evaluated first. Thus you can write:

当然!由于与th:if属性关联的处理器的优先级高于与属性关联的处理器th:text,因此将首先对其进行评估。因此你可以写:

<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>

But I think in this case, whether the summary exist or not, the span tag will be created, which is a bit ugly.

但是我觉得在这种情况下,无论是否存在summary,都会创建span标签,有点难看。

See more info about conditional expressions here.

在此处查看有关条件表达式的更多信息。