Internationalization in Thymeleaf
Want your app in multiple languages? Thymeleaf's i18n support makes it easy to translate every piece of text in your templates.
Using Message Expressions
The #{...} syntax reads text from message files. Create a messages.properties file in your resources.
<p th:text="#{app.welcome}">Welcome</p>
<h1 th:text="#{app.title}">My Application</h1>
In messages.properties, define your keys:
app.welcome=Welcome to our website!
app.title=My Awesome Application
Thymeleaf replaces the keys with the actual text at runtime.
Parameterized Messages
Sometimes you need to insert dynamic values into messages. Use numbered placeholders like {0}, {1}.
greeting.hello=Hello, {0}!
greeting.count=You have {0} new messages.
Pass values using the message expression:
<p th:text="#{greeting.hello('Alice')}"></p>
<p th:text="#{greeting.count(${messageCount})}"></p>
This renders "Hello, Alice!" and "You have 5 new messages."
Locale-Specific Files
Create separate properties files for each language. Spring picks the right one based on the user's locale.
messages.properties
messages_fr.properties
messages_ar.properties
Example French file:
app.welcome=Bienvenue sur notre site!
greeting.hello=Bonjour, {0}!
When a French user visits, they see French text automatically.
Try it Yourself →Switching Locales
You can let users switch languages with a simple link that changes the locale parameter.
<a th:href="@{''(lang='en')}">English</a>
<a th:href="@{''(lang='fr')}">Francais</a>
<a th:href="@{''(lang='ar')}">Arabic</a>
Configure a locale resolver bean in your Spring Boot app to handle the lang parameter and store the preference.
Putting It All Together
Here's a full template using i18n for all text.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="#{app.title}">Title</title>
</head>
<body>
<h1 th:text="#{greeting.hello(${userName})}">Hello</h1>
<p th:text="#{app.description}">Description</p>
<a th:href="@{''(lang='en')}">English</a>
<a th:href="@{''(lang='fr')}">Francais</a>
</body>
</html>
Every piece of user-facing text comes from message files. Change a language, and the entire page updates.