20

在 .jsp 中,我会使用:

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

显示来自我的 messages.properties 文件的消息。

我将如何使用 freemarker 做到这一点?

4

3 回答 3

32

导入 Spring 宏

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

然后

<@spring.message "yourMessageKeyGoesHere"/>

但是你需要注册 ResourceBundleMessageSource

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

请记住 MessageSource必须称为 messageSource

于 2010-07-01T03:17:17.093 回答
14

@布兰克曼

不,您不必在每个模板中手动导入它。您可以在 freemarker 设置中设置 auto_import 属性,如下所示。

<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>
于 2012-05-30T13:54:25.793 回答
2

其他都是很好的答案。为那些使用它的人提供 java config 作为示例。

 @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;
}
于 2016-02-10T18:28:07.773 回答