2016-12-13 58 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>