Thymeleaf:如果属性和属性存在,则显示文本 [英] Thymeleaf: show text if the attribute and property exists

查看:1095
本文介绍了Thymeleaf:如果属性和属性存在,则显示文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果属性和属性存在,百里香中是否有一种简单的方法可以显示属性的内容?如果我的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆