how to use messages with freemarker in spring mvc?

强颜欢笑 提交于 2019-12-03 08:40:19

问题


In a .jsp I would use:

<fmt:message key="welcome.title"/>

to display a message from my messages.properties file.

How would I do this with freemarker ?


回答1:


Import Spring Macro

<#import "/spring.ftl" as spring/>

Then

<@spring.message "yourMessageKeyGoesHere"/>

But you need to register ResourceBundleMessageSource

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="messages"/>
</bean>

Keep in mind MessageSource must be called messageSource




回答2:


@Blankman

No, you don't have to import this manually in each template. You can set an auto_import property in your freemarker settings as showed below.

<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
   ...

   <property name="freemarkerSettings">
        <props>
            <prop key="auto_import">spring.ftl as spring</prop>
        </props>
   </property>
</bean>



回答3:


Others are fine answers. Providing java config as example for those that use that.

 @Bean(name = "freemarkerConfig")
public FreeMarkerConfigurer freemarkerConfig() {
    FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
    configurer.setTemplateLoaderPaths("/WEB-INF/views/", 'classpath:/templates');
    Map<String, Object> map = new HashMap<>();
    map.put("xml_escape", new XmlEscape());
    configurer.setFreemarkerVariables(map)
    def settings = new Properties()
    settings['auto_import']  =  'spring.ftl as spring,layout/application.ftl as l,/macros/meh.ftl as meh'
    configurer.setFreemarkerSettings(settings)
    log.info "returning freemarker config"
    return configurer;
}


来源:https://stackoverflow.com/questions/3154804/how-to-use-messages-with-freemarker-in-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!