Issue
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?
Solution
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>
Answered By - Metroids