使用一个模板和多个language.properties文件比使用多个模板更好。
这会带来一个基本问题:如果我的.vm文件变得很大,包含了许多文本行,那么在单独的资源束(.properties)文件中翻译和管理每个文件将变得繁琐。
如果您的电子邮件结构在多个 .vm 文件上重复,维护起来会更加困难。此外,您还需要重新发明资源束的回退机制。资源束试图在给定区域设置的情况下找到最接近的匹配项。例如,如果区域设置是 en_GB,则它会按顺序查找以下文件,如果没有可用的文件,则回退到最后一个文件。
- language_en_GB.properties
- language_en.properties
- language.properties
我将在此处发布(详细说明)简化 Velocity 模板中读取资源束所需执行的操作。
在Velocity模板中访问资源束
Spring配置
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="content/language" />
</bean>
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="/WEB-INF/template/" />
<property name="velocityProperties">
<map>
<entry key="velocimacro.library" value="/path/to/macro.vm" />
</map>
</property>
</bean>
<bean id="templateHelper" class="com.foo.template.TemplateHelper">
<property name="velocityEngine" ref="velocityEngine" />
<property name="messageSource" ref="messageSource" />
</bean>
模板助手类
public class TemplateHelper {
private static final XLogger logger = XLoggerFactory.getXLogger(TemplateHelper.class);
private MessageSource messageSource;
private VelocityEngine velocityEngine;
public String merge(String templateLocation, Map<String, Object> data, Locale locale) {
logger.entry(templateLocation, data, locale);
if (data == null) {
data = new HashMap<String, Object>();
}
if (!data.containsKey("messages")) {
data.put("messages", this.messageSource);
}
if (!data.containsKey("locale")) {
data.put("locale", locale);
}
String text =
VelocityEngineUtils.mergeTemplateIntoString(this.velocityEngine,
templateLocation, data);
logger.exit(text);
return text;
}
}
Velocity模板
#parse("init.vm")
#msg("email.hello") ${user} / $user,
#msgArgs("email.message", [${emailId}]).
<h1>#msg("email.heading")</h1>
我不得不创建一个简写宏 msg
来从消息包中读取信息。它看起来像这样:
* msg
*
* Shorthand macro to retrieve locale sensitive message from language.properties
*
$messages.getMessage($key,null,$locale)
$messages.getMessage($key,$args.toArray(),$locale)
资源包
email.hello=Hello
email.heading=This is a localised message
email.message=your email id : {0} got updated in our system.
用法
Map<String, Object> data = new HashMap<String, Object>();
data.put("user", "Adarsh");
data.put("emailId", "adarsh@email.com");
String body = templateHelper.merge("send-email.vm", data, locale);