17

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?

2
  • 1
    How about adding a null check inside the fragment itself Commented Dec 13, 2016 at 19:38
  • Do you mean if condition1 != null and condition2 = something? See: stackoverflow.com/questions/31524073/… Commented Apr 17, 2019 at 7:02

2 Answers 2

27

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> 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I was not aware of the Attribute Precedence section!
Thank you. Have been struggling for hours for this :(
13

With Thymeleaf 3.0 you can use the no-operation token to insert/replace only if condition is met, something like this:

<table th:replace="${results} ? ~{fragments :: resultTable} : _"> 

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

1 Comment

nice! this helps when using it to group <link> tags, where I can't add another tag above

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.