ThymeLeaf Fragment 在 false th:if 上执行 [英] ThymeLeaf Fragment executed on false th:if

查看:17
本文介绍了ThymeLeaf Fragment 在 false th:if 上执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<table th:replace="fragments/resultTable" th:if="${results}"><tr><th>人才</th><th>Score</th></tr><tr><td>信心</td><td>1.0</td></tr>

它使用了这个片段:

<tr><th>人才</th><th>Score</th></tr><tr th:each="talent : ${talents}"><td th:text="${talent}">人才</td><td th:text="${results.getScore(talent)}">1.0</td></tr>

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

尝试在空上下文对象上调用方法 getScore(com.model.Talent)

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

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

解决方案

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

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

您可能需要将 th:if 移动到上面的标签中.无论是在容器 div 中,还是如果您仍然需要容器 div,那么 th:block 就像这样:

<th:block th:if="${results}"><table th:replace="fragments/resultTable"><tr><th>人才</th><th>Score</th></tr><tr><td>信心</td><td>1.0</td></tr></th:block>

I'm using Thymeleaf packaged with Spring-Boot. Here is the main template:

<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>

And it uses this fragment:

<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>

The fragment only works if there is a results object. That makes sense to me. So based on the syntax from the documentation I added the th:if statement to the main template file. However I'm still getting this error when I access the template without an object

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

Shouldn't the th:if statement prevent that code from being accessed?

The template still works fine when the results object is populated, but how do I get the null case to render without the table?

解决方案

Fragment inclusion has a higher operator precedence than th:if.

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

You'll probably have to move the th:if to a tag above. Either in the container div, or if you still need the container div, then a th:block like this:

<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>

这篇关于ThymeLeaf Fragment 在 false th:if 上执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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