How to show localization messages with parameters in Spring 3 / Thymeleaf

JavaSpringThymeleaf

Java Problem Overview


I'm using Spring 3 and Thymeleaf to make some webpages and I am lost as for how to show messages like this:

welcome.message=Hello {0}, welcome!

and then replace {0} with the user name inside thymeleaf tags:

<h1 th:text="#{welcome.message}">Welcome Placeholder</h1>

I'm not even sure if {0} is the right syntax for the bundle message.

Java Solutions


Solution 1 - Java

You can use

#{welcome.message(${some.attribute})}

where some.attribute would be the value to use when replacing {0}.

You should be able to comma separate the values between the () to add more values to be used.

Solution 2 - Java

You can even use a calculated message key as a parameter:

<p th:text="#{messages.msg1(${param1})}"></p>
<p th:text="#{messages.msg2(${param2},${param3})}"></p>
<p th:text="#{messages.msg3(#{${param4}})}"></p>

Above, the parameter of [msg3] is a message key [#{key}] where key is itself calculated [${param4}]. The benefit is that you can insert internationalized calculated fragments in an internationalized message.

Solution 3 - Java

If you need to pass an array of parameters where you don't know the size of the array then you can use:

<p th:text="${#messages.msgWithParams(messageKey, messageParams)}"></p>
<!-- or -->
<p th:text="${#messages.msgOrNullWithParams(messageKey, messageParams)}"></p>

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#messages-1

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHoffmannView Question on Stackoverflow
Solution 1 - JavaSotirios DelimanolisView Answer on Stackoverflow
Solution 2 - JavaSerge TahéView Answer on Stackoverflow
Solution 3 - JavaBrett YView Answer on Stackoverflow