SpringBoot + Thymeleaf + i18n (Internationalization)

Hello again.

This week I had to study how to implement i18n in a Spring Boot + Thymeleaf CRM application I am developing. Spring Boot really makes it easy to setup but while I was searching about it on the Web I found a lot of misinformation and so I decided to make a post about it.

As usual, you can find the complete project on Github: https://github.com/mtrojahn/springboot-thymeleaf-i18n.

Let’s start by the pom.xml:

Application.groovy

As you can see, Application.groovy is pretty much the default for any Spring Boot application. I only changed @ComponentScan to lookup the package that contains my HelloWorldController.groovy but I could have easily created both files on the same package to avoid this configuration but hey, let’s do it the right way, right?

The HelloWorldController.groovy is very simple and just directs the “/helloworld” URL to it’s proper view.

And here is the view:

A little explanation is in place here. The <html> tag has a th:lang=”${#locale.language}” which serves the purpose of informing your browser the language that is going to be displayed. This doesn’t have much impact but it’s a good thing to do so you avoid unexpected problems, like indexing by search engines and such.

Bellow you will se the “#{helloworld}” directive. “#{}” tags in Thymeleaf are about messages from i18n files. You won’t need to configure much about it because Spring Boot takes care of most of the work.

message.properties

The message.properties file is where your default language is. Any other language has to have it’s own file and it’s name must be properly formatted. For example:

message_pt_BR.properties

If you use an IDE like Intellij IDEA, dealing with these files is very easy. The IDEA understand them and group them so you can edit these messages in batch.

Here’s the one catch. For your messages to be found you need to configure your application.yml properly

Now you just need to run your project. In my case, my system’s default language is English and I have Portuguese as an additional language pack on my Firefox browser. By default, the application will render in English so the resulting source will be this:

If I change the default language of my browser to Portuguese, this is what I get:

To change the language pack on Firefox, go to Options  / Content and click on Languages:

I hope this post helps you. Leave a comment if you need anything and until the next time!

You may also like...

Leave a Reply

%d bloggers like this: