simplelocalize / spring-boot-i18n

Spring Boot internationalization code and quick guide

Home Page:https://simplelocalize.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

translated spring boot page

Simple internationalization (i18n) for Spring Boot

This project provides a simple guide and code to internationalize your Spring Boot application using default methods for Spring Framework. Step-by-step guide with configuration part is available here.

Project details:

  • Java 19
  • Spring Boot 3.0
  • Thymeleaf
  • Maven
  • SimpleLocalize Editor

simplelocalize

Usage

Get translated messages

Use MessageSource to get translated messages. This is the default way to get translated messages in Spring Boot.

import org.springframework.context.MessageSource;

@Autowired
private MessageSource messageSource;

@Test
void shouldGetTranslatedTextFromLocalFileAndLocale()
{
    //given
    Locale locale = Locale.of("pl", "PL");

    //when
    String titleTextWithArgument = messageSource.getMessage("title", new Object[]{"Foo Bar"}, locale);

    //then
    assert titleTextWithArgument.equals("Hej Foo Bar!");
}

Thymeleaf: render HTML with translations

Use ThymeleafEngine bean to render HTML with translated messages. This is probably the most popular way to render HTML with translated messages in Spring Boot.

@Autowired
private TemplateEngine templateEngine;

public String renderHtmlFromTemplate(Locale locale, String userName)
{
    Context context = new Context();
    context.setLocale(locale);
    context.setVariable("userName", userName);
    context.setVariable("lang", locale.getLanguage());
    context.setVariable("url", "https://simplelocalize.io");
    return templateEngine.process("my-html-template", context);
}

render custom HTML with translated texts

Return translated web pages

You can also return translated web pages (HTML) by using standard Spring Boot @Controller. Spring Boot will automatically resolve user locale and render HTML from my-html-template.html template with translated messages.

This is the default way to return translated web pages in Spring Boot.

@Controller
public class WelcomeController
{
  @GetMapping("/welcome")
  public String renderHtmlFromTemplate(Model model)
  {
    model.addAttribute("userName", "Jakub");
    return "my-html-template";
  }
}

Run the application and open http://localhost:8080/welcome in your browser. You can change the language by adding ?lang=pl_PL to the URL.

changing lang parameter in spring boot

About

Spring Boot internationalization code and quick guide

https://simplelocalize.io


Languages

Language:Java 96.2%Language:HTML 3.8%