栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Velocity / FreeMarker模板的电子邮件国际化

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Velocity / FreeMarker模板的电子邮件国际化

事实证明,使用一个模板和多个language.properties文件胜过拥有多个模板。

这就产生了一个基本的问题:如果我的.vm文件变得很大,包含许多行文本,那么在单独的资源包(.properties)文件中转换和管理它们的每个文件就变得很乏味。

如果您的电子邮件结构在多个

.vm
文件中重复,则更难维护。同样,人们将不得不重新发明资源束的后备机制。资源束尝试找到给定语言环境的最接近匹配项。例如,如果语言环境为
en_GB
,它将尝试按顺序查找以下文件,如果没有可用的文件,则回退到最后一个文件。

  • language_zh_CN.properties
  • language_zh.properties
  • language.properties

我将在此处发布(详细)为简化读取Velocity模板中的资源包而必须做的事情。

在Velocity模板中访问资源包

弹簧配置

<bean id="messageSource" >    <property name="basename" value="content/language" /></bean><bean id="velocityEngine" >        <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" >    <property name="velocityEngine" ref="velocityEngine" />    <property name="messageSource" ref="messageSource" /></bean>

TemplateHelper类

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=Helloemail.heading=This is a localised messageemail.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);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/428960.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号