我想用一个使用国际化的小胡子模板构建一个spring boot web应用程序。
按照本指南https://www.baeldung.com/spring-boot-internationalization,我尝试了一个带有gradle和kotlin的迷你示例,它与百里叶模板一起使用但是没有留下胡子
为了适应小胡子指南,我做了以下更改:
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
切换implementation 'org.springframework.boot:spring-boot-starter-mustache'
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>{{#i18n}}greeting{{/i18n}} test</h1>
</body>
</html>
文件messages.properties包含行greeting=Hello! Welcome to our website!
只是为了提供所有必要的代码,这是我的配置类
@Configuration
@ComponentScan(basePackages = ["com.example.translationtest.config"])
class AppConfig: WebMvcConfigurer {
@Bean
fun localeResolver(): LocaleResolver {
val slr = SessionLocaleResolver()
slr.setDefaultLocale(Locale.US)
return slr
}
@Bean
fun localeChangeInterceptor(): LocaleChangeInterceptor {
val lci = LocaleChangeInterceptor()
lci.paramName = "lang"
return lci
}
override fun addInterceptors(registry: InterceptorRegistry) {
registry.addInterceptor(localeChangeInterceptor())
}
}
当我在浏览器中访问该页面时,我只看到字符串test
,而我希望看到
Hello! Welcome to our website! test
JMustache使用的spring-boot-starter-mustache
不提供开箱即用的任何国际化支持。由于JMustache无法识别{{#i18n}}greeting{{/i18n}}
,因此模板中的i18n
将被忽略。
如其自述文件中所述,您可以使用Mustache.Lamda
实现国际化支持:
您还可以获取片段执行的结果,以执行国际化或缓存等操作:
Object ctx = new Object() { Mustache.Lambda i18n = new Mustache.Lambda() { public void execute (Template.Fragment frag, Writer out) throws IOException { String key = frag.execute(); String text = // look up key in i18n system out.write(text); } }; }; // template might look something like: <h2>{{#i18n}}title{{/i18n}</h2> {{#i18n}}welcome_msg{{/i18n}}
添加Andy Winlkinson回答和加入Rotzlucky期望我分享我为实现JMustache国际化工作所做的工作。
@ControllerAdvice
public class InternacionalizationAdvice {
@Autowired
private MessageSource message;
@ModelAttribute("i18n")
public Mustache.Lambda i18n(Locale locale){
return (frag, out) -> {
String body = frag.execute();
String message = this.message.getMessage(body, null, locale);
out.write(message);
};
}
}