以下の内容はhttps://ti-tomo-knowledge.hatenablog.com/entry/2018/06/16/225947より取得しました。


Spring Boot Thymeleafで多言語化


多言語対応でサイトを作ることが多い現代だからなのか、
最近のフレームワークは多言語対応がとても簡単です。

ここではThymeleafに表示される文字を多言語対応する方法を共有します。
基本的にはmessages_ja.propertiesや、messages_en.propertiesというような各国ごとのpropertiesファイルに「キー + 単語」を入れていくだけなのですが、
デフォルトの設定ではそのようなpropertiesファイルを読み込む設定がされていません。
なので、まずは以下のようなWebMvcConfigurerAdapterを継承したクラスを設定してください。

package テストパッケージ;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 
@Configuration
public class MessageConfig extends WebMvcConfigurerAdapter {
 
    @Bean
    ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        // ここから先でどこのファイルを読めばよいのか指定してます。
        // MessageSource → メッセージの読み込み元ですからね
        messageSource.setBasenames("classpath:i18n/messages");
        messageSource.setCacheSeconds(0);
        messageSource.setDefaultEncoding("UTF-8");
        // ここまで
        return messageSource;
    }
}

他のサイトを参考にすると、
application.propertiesに設定値を入れればできるという内容が多かったですが、
なぜか僕の場合はできませんでした...

これで例えばmessages_ja.propertiesに、

test=テストだよ

と書いて、

Thymeleafに

<p th:text="#{test}"></p>

と書けば以下のようなタグが生成されます。

<p>テストだよ</p>

以下のような書き方をしても意味がないので注意してくださいね。

<p>#{test}</p>


  • 作者:俊明, 槙
  • 発売日: 2016/09/01
  • メディア: 単行本




以上の内容はhttps://ti-tomo-knowledge.hatenablog.com/entry/2018/06/16/225947より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14