【问题标题】:Thymeleaf: show text if the attribute and property existsThymeleaf:如果属性和属性存在则显示文本
【发布时间】:2014-02-27 00:59:01
【问题描述】:

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

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

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

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>

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

【问题讨论】:

    标签: spring thymeleaf spring-el


    【解决方案1】:

    当然!由于与th:if 属性关联的处理器具有higher precedence 而不是与th:text 属性关联的处理器,因此将首先评估它。因此你可以写:

    <span th:if="${error != null && error.summary != null}" th:text="${error.summary}">Static summary</span>
    

    您甚至可以使用以下方法缩短它:

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

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

    查看更多关于条件表达式的信息here

    【讨论】:

    • 坦克。正是我想要的。
    • @tduchateau 如果不需要&lt;span&gt;标签,我们可以使用th:remove="tag"对吧?
    • 条件表达式的链接失效了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多