Thymeleafで多言語対応を実装

Thymeleafで多言語対応を実装

Thymeleafで多言語対応を実装するには、以下の手順を行います。

1. メッセージプロパティファイルを作成
2. Thymeleafテンプレートでプロパティを参照
3. SpringBoot設定を行う

1. メッセージプロパティファイルを作成

src/main/resourcesディレクトリに、以下のようなプロパティファイルを作成します。

messages.properties(デフォルトの言語、ここでは英語)

greeting=Hello, World!

messages_ja.properties(日本語)

greeting=こんにちは、世界!

2. Thymeleafテンプレートでプロパティを参照

Thymeleafテンプレートファイル(例: index.html)で、プロパティを以下のように参照します。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>多言語対応の例</title>
</head>
<body>
  <h1 th:text="#{greeting}">Hello, World!</h1>
</body>
</html>

3. SpringBoot設定を行う

application.propertiesに以下の設定を追加します。

spring.messages.basename=messages
spring.messages.encoding=UTF-8

Controllerクラスでロケールを設定し、対応するメッセージを表示するようにします。

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Locale;

@Controller
public class GreetingController {

  @GetMapping("/greeting")
  public String greeting(Model model, Locale locale) {
    model.addAttribute("locale", locale);
    return "index";
  }
}

これで、ユーザーのブラウザの言語設定に基づいて、適切な言語のメッセージが表示されます。