'Thymeleaf - i18n get back the template by locale and custom parameter
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
For i18n I have a different approach. My thymeleaf HTML template namings are the following (similar to Freemaker templating):
templatename_default_FOO.html
templatename_en_EN_FOO.html
templatename_de_DE_FOO.html
templatename_default_ANOTHER.html
templatename_en_EN_ANOTHER.html
templatename_de_DE_ANOTHER.html
The convention is:
- templatename - is the name of the template
- default/en_EN/de_DE - is the locale which I get from an API - The locale may not exists in the templates, in this case I want to use the default template with the matching user parameter
- FOO/ANOTHER - different parameter values which the users sets - they exists in atleast one template's name (the default should contain it)
Previously I used ResourceBundles to get the templates by locale if existed, otherwise the default value was automatically chosen. However with Thymeleaf implementation I don't know how to implement the same mechanics, because currently I get the template by providing the full name. If I add a locale which not exists I don't get back the default template.
Question
I know that i18n in Thymeleaf is done through language.properties, but in my case I would need a function where I provide the template name, the locale and the user parameter and I get back the specified HTML file if exists and if not the default HTML file with the matching user parameter.
Something similar:
public String getTemplate(Map<String, Object> myProperties, String templateName, Locale locale, String userParameter) {
Context context = new Context();
context.setVariables(myProperties);
return templateEngine.process(templateName, locale, userParameter context);
}
Is that possible somehow or I should use language.properties? Or I should write custom logic to check if the template not exists go with the default one?
Thanks in advance
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
