Reputation: 86697
I have a thymeleaf html
page that shows all rows from a database @Entity
.
Problem: the entity has a complex field that is mapped with a hibernate AttributeConverter
. When I want to show the field as String
in html, I have to call that converter to onvert the complex field to a string representation, like:
<td th:text="${{T(org.exmaple.domain.utils.AddressConverter).convertToString(row?.address)}}" />
With source:
//assume I have the address only in this format
public class AddressConverter<Address, String> {
public String convertToString(Address address) {
if (address == null) return null;
return address.getZip() + " " + address.getTown();
}
}
Question: how can I optimize those utility imports in thymeleaf? I'm looking for something simple like:
<td th:text="${{addressUtil.convertToString(row?.address)}}" />
Upvotes: 1
Views: 244
Reputation: 86697
I just found out that spring beans can simply be accessed with the @
parameter, like:
<div th:text="${@addressConverter.convertToString()}">...</div>
Of course this assumes it's not a static utility.
If anybody knows how to better expose a static utility to thymeleaf, please answer.
Upvotes: 0
Reputation: 6912
Let's go backward, starting from your requirements. The following is something you would like to have in your Thymeleaf template ...
<td th:text="${addressConverter.convertToString(row?.address)}" />
To call addressConverter
's function convertToString
like this, you would need to have the object available in your model. Basically in your controller have a static variable ...
private static final AddressConverter addressConverter = new AddressConverter();
And after add it to the model ...
model.addAttribute("addressConverter", addressConverter);
Upvotes: 1