Yev
Yev

Reputation: 337

spring/thymeleaf i18n for database content

I have to localize the existing application written in thymeleaf and spring 4. For static content the creation of messages_FR.properties and messages_ES.properties and traditional Spring i18n strategy works well.

The problem comes from dynamic content (stored in the database record). The previous version of content was displayed by th:text="${product.title}".

Now the database content have been localized by duplicating the fields with lang suffix, so for the table product and row title I have two additional rows title_ES and title_FR

and now I need to make this display local specific, i.e. for french local it should use th:text="${product.title_FR}" or something like th:text=${@beans.i18n(product.title)}

What is the recommended way to implement such logic?

Any help is appreciated.

Upvotes: 2

Views: 1410

Answers (1)

Martin Frey
Martin Frey

Reputation: 10075

You have several possibilities:

  • use your own bean like your i18n and use th:text. You can use the LocaleContextHolder to access the locale of the request (not fully sure on the name). Your will have full control of how to resolve the keys.
  • write a MessagesResolver that resolves keys against the database. Then you use the standard expression for i18n: #{...}. You might need to take care of cache eviction as messageresolution is using an internal cache.

Writing your own dialect is not necessary as this is most of the time just to wrap some bean calls in a nicer syntax.

Probably the simplest approach is to use a bean and adapt the text expressions accordingly. The second approach has the advantage that all messages will be resolvable against the database and you could easily override the values inside the property files at runtime.

Upvotes: 2

Related Questions