這個問題在這里已經有了答案: Spring boot Thymeleaf 中的 I18n 1 個答案 9 小時前關閉。
情況
我正在使用帶有 Thymeleaf 的 Spring Boot 來填充我的 HTML 模板檔案并將結果作為字串回傳。為此,我使用了SpringTemplateEngine.
代碼看起來像這樣
Context context = new Context();
context.setVariables(myProperties);
return templateEngine.process(htmlTemplateName, context);
我想實作類似的問題,但使用 language.property 檔案
我有兩個語言屬性檔案:language.properties 和 language_en.properties,看起來像這樣
my.value = This a string containing a dummy name = {name}
我想達到什么目的?
- 我想使用 thymeleaf 來訪問正確的語言屬性檔案
- 用定義的變數填充
{name}變數。模板應基于 HTML 中的變數名稱,例如:hashmap: <"name", "FooName"> - 將填充的文本作為字串取回。我沒有 HTML 檔案,我只想使用 thymeleaf 的模板機制。
問題
有可能嗎?我該怎么做?如果可能的話,language.properties 中的正確格式是什么?
uj5u.com熱心網友回復:
是的你可以!
您需要為MessageSource資源目錄中的訊息檔案配置一個具有正確基本名稱的 bean,例如:
spring.messages.basename=path/to/language,假設您的屬性檔案位于path/to/language(_en).properties
給定這個 bean,無論您需要翻譯的字串,您注入一個實體Messages并使用它來獲取給定訊息的翻譯字串key:
public class I18NHelper {
private final Messages messages;
public I18NHelper(final Messages messages) {
this.messages = messages;
}
public String translate(String key, String name) {
return messages.getMessage(key, name);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/475955.html
