我正在为IBM Connections开发Java应用程序,而我的应用程序需要生成和发送基于模板的电子邮件。
连接包括几个使用资源包的Freemarker模板。我希望我的代码使用它们的副本进行最少的更改,但是我以前从未使用过Freemarker。

在我的Java代码中,如何使资源包与Freemarker模板相关联,以使现有模板能够正常工作?

模板和资源包位于以下目录结构中:

notifications (directory)
-> activities (directory)
  -> resources (directory)
    -> nls (directory)
      -> properties files
  -> Template FTL files
-> resources (directory)
  -> nls (directory)
    -> properties files
  -> Imported FTL files

One of the main template files is "notifyMail.ftl". Some lines of particular interest in that file are:

<#import "*/resources/commonStructure.ftl" as s>
<#import "*/resources/commonUtil.ftl" as u>
<#import "*/resources/commonUrlUtil.ftl" as urlUtil>
<#lt><@s.header>${u.resource("email.notify.body."+"${key}","${activity.event.sender.display.name}",urlUtil.linkifyItem("${activity.node.permalink}", "${activity.node.name}"))}</@s.header>


“ commonUtil.ftl”文件声明了两个使用资源包的函数,如下所示。
第一个函数使用称为“ __parameters”的成员。
我假设需要在Java代码中将其传递给Freemarker,因为我看不到模板中的任何地方都定义了它。

<#function resource messageKey params...>
    <#if __parameters.__resourceBundle?keys?seq_contains(messageKey)>
        <#local bundleString = bundleResource(__parameters.__resourceBundle,messageKey,params) />
    <#elseif __parameters.__sharedBundle?keys?seq_contains(messageKey)>
        <#local bundleString = bundleResource(__parameters.__sharedBundle,messageKey,params) />
    <#else>
        <#return messageKey /> <#-- message key not found, return the key back -->
    </#if>

    <#if bundleString??>
        <#return bundleString />
    <#else>
        <#return messageKey />
    </#if>
</#function>

<#function bundleResource bundle messageKey params>
<#if bundle??>
<#switch params?size>
<#case 0>
    <#return bundle(messageKey)>
    <#break>
<#case 1>
    <#return bundle(messageKey, params[0])>
    <#break>
<#case 2>
    <#return bundle(messageKey, params[0], params[1])>
    <#break>
<#case 3>
    <#return bundle(messageKey, params[0], params[1], params[2])>
    <#break>
<#case 4>
    <#return bundle(messageKey, params[0], params[1], params[2], params[3])>
    <#break>
<#case 5>
    <#return bundle(messageKey, params[0], params[1], params[2], params[3], params[4])>
    <#break>
<#default>
    <#stop "resource function doesn't support more than 5 parameters for a message due to language reason. And it's seldom to have more than 5 parameters in a message. However, you can extend the limit by changing the function if you really want to."/>
</#switch>
</#if>
</#function>

最佳答案

事实证明,此解决方案很简单,尽管由于我的属性文件存在问题,我很难使消息格式正常工作。

我发送到Mapfreemarker.template.Template.process()仅需要Fcc文件所使用的相同层次结构中的ResourceBundle实例。

例如。 FTL文件具有以下内容:

__parameters.__resourceBundle


我的Java源代码中有一个notification.properties文件,并将其添加到发送到Freemarker的地图中,如下所示:

HashMap tmplParams=new HashMap();

tmplParams.put("__resourceBundle",ResourceBundle.getBundle(
    "<parent directory path>.activities.resources.nls.notification"));

root.put("__parameters",tmplParams);

09-10 08:03
查看更多