【问题标题】:ThymeLeaf Fragment executed on false th:ifThymeLeaf 片段在错误 th:if 上执行
【发布时间】:2017-04-28 23:31:53
【问题描述】:

我正在使用与 Spring-Boot 一起打包的 Thymeleaf。这是主要模板:

<div class="container">
    <table th:replace="fragments/resultTable" th:if="${results}">
        <tr>
            <th>Talent</th>
            <th>Score</th>
        </tr>
        <tr>
            <td>Confidence</td>
            <td>1.0</td>
        </tr>
    </table>
</div>

它使用了这个片段:

<table th:fragment="resultTable">
    <tr>
        <th>Talent</th>
        <th>Score</th>
    </tr>
    <tr th:each="talent : ${talents}">
        <td th:text="${talent}">Talent</td>
        <td th:text="${results.getScore(talent)}">1.0</td>
    </tr>
</table>

片段仅在有结果对象时才有效。这对我来说很有意义。因此,基于documentation 的语法,我将th:if 语句添加到主模板文件中。但是,当我在没有对象的情况下访问模板时仍然出现此错误

Attempted to call method getScore(com.model.Talent) on null context object

th:if 语句不应该阻止该代码被访问吗?

填充结果对象后,模板仍然可以正常工作,但是如何在没有表格的情况下呈现 null 情况?

【问题讨论】:

标签: spring-mvc spring-boot thymeleaf


【解决方案1】:

使用 Thymeleaf 3.0,您可以使用无操作令牌仅在满足条件时插入/替换,如下所示:

<table th:replace="${results} ? ~{fragments :: resultTable} : _">

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#advanced-conditional-insertion-of-fragments

【讨论】:

    【解决方案2】:

    片段包含的运算符优先级高于 th:if。

    http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#attribute-precedence

    您可能必须将 th:if 移动到上面的标记中。在容器 div 中,或者如果您仍然需要容器 div,则 th:block 像这样:

    <div class="container">
        <th:block th:if="${results}">
            <table th:replace="fragments/resultTable">
                <tr>
                    <th>Talent</th>
                    <th>Score</th>
                </tr>
                <tr>
                    <td>Confidence</td>
                    <td>1.0</td>
                </tr>
            </table>
        </th:block>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2014-08-29
      • 2015-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-22
      • 2017-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多