ThymeLeaf Fragment在假的情况下执行:if

gri*_*gon 8 spring-mvc thymeleaf spring-boot

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

<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>
Run Code Online (Sandbox Code Playgroud)

它使用这个片段:

<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>
Run Code Online (Sandbox Code Playgroud)

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

Attempted to call method getScore(com.model.Talent) on null context object
Run Code Online (Sandbox Code Playgroud)

th:if语句是否应该阻止访问该代码?

填充结果对象时模板仍然可以正常工作,但是如何在没有表的情况下渲染null case?

小智 11

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

<table th:replace="${results} ? ~{fragments :: resultTable} : _">
Run Code Online (Sandbox Code Playgroud)

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


Met*_*ids 10

片段包含具有比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>
Run Code Online (Sandbox Code Playgroud)