spring-boot - 为什么我的Spring Boot应用程序不在 mustache 模板中呈现messages.properties

标签 spring-boot gradle kotlin mustache

我想使用使用国际化的 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'
  • 将international.html重命名为international.mustache
  • 更改这样的international.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/

    相关文章:

    spring - 如何编写一个 RestController 从 XML 请求更新 JPA 实体,Spring Data JPA 方式?

    java - AbstractMethodError:org.apache.bval.jsr303.ConfigurationImpl 缺少方法 getDefaultParameterNameProvider() 的定义

    java - 如何通过 Flyway 使用 Spring Boot/Spring Security 的 JDBC 身份验证

    java - Kotlin 编译库失败

    java - 在Kotlin/Java中将列表过滤到特定大小

    java - NoSuchBeanDefinition 异常

    jenkins - 如何解决Jenkins测试实例中的插件加载问题

    android - 如何修复 `duplicate class com.google.firebase.components`?

    java - 调用具有相同前缀的不同变量只改变后缀

    android - 如何使用挂起函数作为参数在 View 模型中初始化流