事实证明,使用一个模板和多个 language.properties 文件胜过使用多个模板。
这会产生一个基本问题:如果我的 .vm 文件变大
多行文本,翻译和管理每一行变得繁琐
它们在单独的资源包 (.properties) 文件中。
如果您的电子邮件结构在多个 .vm 文件中重复,则更难维护。此外,还必须重新发明资源包的后备机制。资源包尝试在给定语言环境的情况下找到最接近的匹配项。例如,如果语言环境是en_GB,它会尝试按顺序查找以下文件,如果没有一个可用,则回退到最后一个。
- language_en_GB.properties
- language_en.properties
- language.properties
我将在此处发布(详细)我为简化阅读 Velocity 模板中的资源包而必须做的事情。
在 Velocity 模板中访问资源包
弹簧配置
<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;
}
}
速度模板
#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
*#
#macro(msg $key)
$messages.getMessage($key,null,$locale)
#end
#macro(msgArgs $key, $args)
$messages.getMessage($key,$args.toArray(),$locale)
#end
资源包
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);