Velocity模板 - 消息键而不是带占位符的整个短语

时间:2017-01-06 11:33:58

标签: java velocity email-templates

我有电子邮件模板.vm,其中包含来自messages_en.properties的消息密钥的消息:

#msg("email-body")

messages_en.properties有:

email-body = Hello, $name!

后:

private String buildMessage(String templateName, Properties properties, Locale locale) {

    Template template = getVelocityEngine().getTemplate(templateName);

    VelocityContext context = new VelocityContext();

    for (String key : properties.stringPropertyNames()) {
        context.put(key, properties.getProperty(key));
    }

    context.put(LocaleDirective.MESSAGES_LOCALE, locale);

    StringWriter writer = new StringWriter();
    template.merge(context, writer);

    return writer.toString();
}

我明白了:

Hello, $name!

并且名称未被实际值替换。

管理电子邮件模板中短语的最佳方法是什么?我想只在模板中放入消息密钥,而不是整个带占位符的短语。

1 个答案:

答案 0 :(得分:1)

在其他变量中使用evaluate指令代替变量:

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.RuntimeSingleton;
import org.apache.velocity.runtime.parser.node.SimpleNode;

import java.io.StringReader;
import java.io.StringWriter;

public class Main {

    public static void main(String[] args) throws Exception {
        RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
        StringReader reader = new StringReader("#evaluate($email-body)");
        SimpleNode node = runtimeServices.parse(reader, "default");

        Template template = new Template();
        template.setRuntimeServices(runtimeServices);
        template.setData(node);
        template.initDocument();


        VelocityContext context = new VelocityContext();
        context.put("name", "Maxim");
        context.put("email-body", "Hello, $name!");

        StringWriter writer = new StringWriter();
        template.merge(context, writer);

        System.out.println(writer.toString());
    }
}

输出:

Hello, Maxim!