我想使用使用国际化的 mustache 模板构建Spring Boot Web应用程序。
按照本指南https://www.baeldung.com/spring-boot-internationalization,我尝试了一个带有gradle和kotlin的迷你示例,该示例可与百里香模板一起使用,但因 mustache 而失败
为了使该指南适用于 mustache ,我进行了以下更改:
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
最佳答案
spring-boot-starter-mustache
使用的JMustache并没有提供任何国际化支持。模板中的{{#i18n}}greeting{{/i18n}}
被忽略,因为JMustache无法识别i18n
。
如其自述文件所述,您可以使用Mustache.Lamda
实现国际化支持:
You can also obtain the results of the fragment execution to do things like internationalization or caching:
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}}
关于spring-boot - 为什么我的Spring Boot应用程序不在 mustache 模板中呈现messages.properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54225243/