PaulJK
PaulJK

Reputation: 301

Spring Boot i18n + Thymeleaf: using arrays in the messages.properties files

I'm building a Spring Boot website with i18n and three languages. This means that when I have a select input with several strings in a form (e.g. choosing apple/banana/carrot), I can't just put these strings in the template, I have to run them through the messages bundle. I figured out that I can simply use numeric values in the select input like this:

<option value="1" th:text="#{user.function[1]}">Lorem</option>
<option value="2" th:text="#{user.function[2]}">Ipsum</option>
<option value="3" th:text="#{user.function[3]}">Dolor</option>
<option value="4" th:text="#{user.function[4]}">Sit</option>
<option value="5" th:text="#{user.function[5]}">Amet</option>

And then pull the actual strings from an array in the messages properties file which for English looks like this:

user.function[1]=Lorem
user.function[2]=Ipsum
user.function[3]=Dolor
user.function[4]=Sit
user.function[5]=Ames

This seems to work OK for pulling the data, because I can display e.g. "Dolor" in a template like this:

th:text="#{user.function(3)}"

The problem arises when instead of simple "3" I need to use a field from a database, e.g. user.function:

th:text="#{user.function(${user.function})}"

Even though ${user.function} returns 3, the line above just returns:

??user.function_en??

What am I doing wrong?

Upvotes: 1

Views: 617

Answers (1)

Prebiusta
Prebiusta

Reputation: 479

It's because you are trying to evaluate inner expression. Official Thymeleaf documentation says

´__${...}__´ syntax is a preprocessing expression, which is an inner expression that is evaluated before actually evaluating the whole expression

You can read more here https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#dynamic-fields

You could try something like this

th:text="#{user.function(__${user.function}__)}"

This means that inner user.function will be evaluated before outer user.function

Upvotes: 1

Related Questions