【问题标题】:Thymeleaf - skip table creation if the iterated list is nullThymeleaf - 如果迭代列表为空,则跳过表创建
【发布时间】:2021-06-02 14:15:46
【问题描述】:

我有一个 html thymeleaf 模板,我在其中构建了一个迭代列表的表:

    <table>
        <tr>
            <th>Setup Name</th>
            <th>Setup Path</th>
        </tr>
        <tr th:each="setup : ${upgradeState.targetUpgradeSetups.setups}">
            <td th:text="${setup.name}"/>
            <td th:text="${setup.path}"/>
        </tr>
    </table>

问题是元素upgradeState.targetUpgradeSetups可能是null,所以我想只在元素不为空的时候建这个表。

注意:如果元素upgradeState.targetUpgradeSetups 不是null,那么保证列表setups 也不为空。因此我只需要检查父元素。

我尝试使用th:if 语句如下:

<tr th:if=${upgradeState.targetUpgradeSetups != null} th:each="setup : ${upgradeState.targetUpgradeSetups.setups}">

但即便如此,我仍然遇到同样的异常:

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'setups' cannot be found on null
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:213)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:104)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.access$000(PropertyOrFieldReference.java:51)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference$AccessorLValue.getValue(PropertyOrFieldReference.java:406)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:90)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:109)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:328)
    at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:263)
    ... 74 more

我没有找到关于 Thymeleaf 的特定示例/参考来解决此类问题,有人可以建议正确的方法吗?

【问题讨论】:

    标签: java spring-boot thymeleaf


    【解决方案1】:

    您需要依靠 Thymeleaf Attribute Precedence。根据顺序,Thymeleaf 将首先解析迭代,并且仅在条件之后,当放置到同一个标签中时。适合您的代码可能看起来像...

    <table>
        <tr>
            <th>Setup Name</th>
            <th>Setup Path</th>
        </tr>
        <tbody th:if=${upgradeState.targetUpgradeSetups != null}>
        <tr th:each="setup : ${upgradeState.targetUpgradeSetups.setups}">
            <td th:text="${setup.name}"/>
            <td th:text="${setup.path}"/>
        </tr>
        </tbody>
    </table>
    

    【讨论】:

    • 你说得对,非常感谢!
    • 我建议稍作修改。你能检查一下吗? :)
    • @RukshanJayasekara 嗨,Rukshan,我宁愿保留示例而不删除null 的显式检查,因为这是 OP 测试对象的方式。我假设 OP 想要对可读性进行明确的检查。随它吧。感谢您的建议。
    • @RukshanJayasekara 我不太喜欢测试指针的方式,我觉得它令人困惑(你不知道你是在测试 null 还是在测试布尔值)。很高兴知道非常感谢您的建议,但我确实更喜欢留下明确的检查:)
    猜你喜欢
    • 2018-06-09
    • 1970-01-01
    • 2020-12-29
    • 2015-12-12
    • 1970-01-01
    • 2020-06-28
    • 2013-09-03
    • 2017-03-25
    • 2017-08-29
    相关资源
    最近更新 更多