Localized template lookups (Freemarker style)
See original GitHub issueFreemarker (by default) uses the locale to build the file names it looks for when loading and including templates. For example, loading tos.ftl
(the template) with the en_US
locale would look for these template files in order and use the first one it finds:
- tos_en_US.ftl
- tos_en.ftl
- tos.ftl
This can be useful to translate whole pages when the pages are completely different between different languages. For example, a “Terms of Service” page might be mostly static so different languages would have completely different content. In this case, it is a hassle to externalize the whole content to messages loaded from message bundles. i know it is possible to use th:if
which toggle sections based on the current locale but it’s not as easy to navigate between different languages using this.
Could such a lookup mechanism be added to Thymeleaf?
Issue Analytics
- State:
- Created 7 years ago
- Reactions:5
- Comments:6 (2 by maintainers)
Top GitHub Comments
With the current Thymeleaf 3.0 APIs, an implementation of
ITemplateResolver
could be created that resolved a different template for each locale by means of specifying such locale in thetemplateResolutionAttributes
map that can be passed as a parameter to theITemplateEngine.process(...)
methods.However, this would mean you’d need to actually pass the locale twice: once in the
IContext
and another time in thetemplateResolutionAttributes
, and of course make sure it is the same locale.In 3.0 there is probably no better way of doing this, because template resolution is a separate phase from that of actual template process, and the results of template resolution might be cached without explicitly depending on the locale as a part of the cache key — though the
templateResolutionAttributes
will be a part of such cache key, so you should be fine using it.I’m leaving this in the Wish List so that we can evaluate the possibility of creating some kind of locale-oriented specific template resolution functionalities in next versions.
@berniegp I have this feature working with current stable Thymeleaf 3, being implemented this way: https://github.com/resource4j/resource4j/blob/master/integration/thymeleaf3/src/main/java/com/github/resource4j/thymeleaf3/Resource4jTemplateEngine.java
You can try this solution as a workaround with your own template resolver.