Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access inner objects in Thymeleaf?

I am trying to Iterate a List if Users using thymeleaf,

My User object is like this

public class User implements java.io.Serializable {

    private Integer userId;
    private Department department;
    private String email;
    // setters and getters etc
}

and department object is like this

public class Department implements java.io.Serializable {

    private Integer departmentId;
    private String name;
    // setters and getters etc
}

in thymeleaf I do this

<tr th:each="user : ${users}">
    <td th:text="${user.email}"></td>
    <td th:text="${user.department.name}"></td>
</tr>

and I am getting this error

org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "user.department.name"

if I use only user.email, there is no issues.

So how to access inner objects in in Thymeleaf EL? (In my case user.department.name)

like image 579
Arun Xavier Avatar asked Jun 25 '26 21:06

Arun Xavier


1 Answers

You are accessing it correctly, but you will get an exception if the department on the user is null.

What you can do is use null safe dereferencing using the '?' operator, i.e.

<td th:text="${user.department?.name}"></td>

This will check first whether department is null. See Spring EL's Safe Navigation Operator

like image 77
Willy du Preez Avatar answered Jun 28 '26 13:06

Willy du Preez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!