java 如何在 spring mvc 中使用带有 freemarker 的消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3154804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use messages with freemarker in spring mvc?
提问by Blankman
In a .jsp I would use:
在 .jsp 中,我会使用:
<fmt:message key="welcome.title"/>
to display a message from my messages.properties file.
显示来自我的 messages.properties 文件的消息。
How would I do this with freemarker ?
我将如何使用 freemarker 做到这一点?
回答by Arthur Ronald
Import Spring Macro
导入 Spring 宏
<#import "/spring.ftl" as spring/>
Then
然后
<@spring.message "yourMessageKeyGoesHere"/>
Butyou need to register ResourceBundleMessageSource
但是需要注册ResourceBundleMessageSource
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
Keep in mind MessageSource must be calledmessageSource
请记住 MessageSource必须称为messageSource
回答by matthaeus
@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.
不,您不必在每个模板中手动导入它。您可以在 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>
回答by Matthew Payne
Others are fine answers. Providing java config as example for those that use that.
其他都是很好的答案。为那些使用它的人提供 java 配置作为示例。
@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;
}

