为什么我的spring启动应用程序不会在mustache模板中呈现messages.properties

问题描述 投票:0回答:2

我想用一个使用国际化的小胡子模板构建一个spring boot web应用程序。

按照本指南https://www.baeldung.com/spring-boot-internationalization,我尝试了一个带有gradle和kotlin的迷你示例,它与百里叶模板一起使用但是没有留下胡子

为了适应小胡子指南,我做了以下更改:

  1. implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'切换implementation 'org.springframework.boot:spring-boot-starter-mustache'
  2. 将international.html重命名为international.mustache
  3. 改变国际。这样的话 <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 gradle kotlin mustache
2个回答
1
投票

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}}

0
投票

添加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);
        };
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.