Sivaram Surapureddy
Sivaram Surapureddy

Reputation: 11

How to map nested objects in thymeleaf

I have class structure similar to

Class1 { Class2{ Attribute1 } Class3 { Attribute2 } }

Now i have to map the html fields to the attributes how can I do the attributes under inner classes in thymeleaf springboot

Upvotes: 0

Views: 1645

Answers (2)

Metroids
Metroids

Reputation: 20487

As long as your getters and setters are correctly set up, you can dot-walking to access inner objects and properties:

<span th:text="${class1.class2.attribute1}" />
<span th:text="${class1.class3.attribute2}" />

If you are using those attributes in a form, the same works for input fields. For example:

<form th:object="${class1}">
    <input type="text" th:field="*{class2.attribute1}" />
</form>

Upvotes: 1

madaimartin
madaimartin

Reputation: 99

The answer of Metroids seems to be correct. If you get an error, make sure again you have getters and setters in your Java classes and their modifier are public. Missing it is a common mistake.
Also make sure this attributes are exists and you did not misstype it. If you get NullPointerException, you should use #{objects.nullsafe(variable)} or use ?s like this:
<td th:text="${user?.address?.street}"></td>

The ? means this object or attribute can be null.
I hope I could help you. :)

Upvotes: 0

Related Questions