2016-12-13 57 views
4

我使用与Spring-Boot打包的Thymeleaf。这里是主模板:ThymeLeaf片段执行错误th:如果

<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声明防止代码被访问?

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

+1

如何将片段本身内部空校验 –

回答

3

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

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

你可能必须移动日:如果标签上面。无论是在div容器,或者如果你仍然需要div容器,然后一个个:块这样的:

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