Issue
Circumstances
I'm using Spring Boot with Thymeleaf for populating my HTML template files and get back the result as a String. For that I used SpringTemplateEngine
.
The code looks like this
Context context = new Context();
context.setVariables(myProperties);
return templateEngine.process(htmlTemplateName, context);
The problem I want to achieve something similar, but with language.property files
I have two language property files: language.properties and language_en.properties which looks like this
my.value = This a string containing a dummy name = {name}
What I want to achieve?
- I want to use thymeleaf to reach the correct language property file
- Populate the
{name}
variable with a defined variable. The templating should be based on variable name like in HTMLs eg: hashmap: <"name", "FooName"> - Get back the populated text as String. I don't have HTML file, I just want to use the templating mechanism of the thymeleaf.
Question
Is it possible and how can I do that? What is the right formatting in language.properties if it's possible?
Solution
Yes, you can!
You need to configure a MessageSource
bean with the correct basename to your message files in your resource directory, like:
spring.messages.basename=path/to/language
, assuming your properties files are located at path/to/language(_en).properties
Given this bean, wherever you need a translated string, you inject an instance of Messages
and use that to get your translated string for a given message key
:
public class I18NHelper {
private final Messages messages;
public I18NHelper(final Messages messages) {
this.messages = messages;
}
public String translate(String key, String name) {
return messages.getMessage(key, name);
}
}
Answered By - kistlers
Answer Checked By - David Goodson (JavaFixing Volunteer)