我有电子邮件模板 .vm,其中包含带有来自 messages_en.properties 的消息 key 的消息:
#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!
并且名称不会替换为实际值。
管理电子邮件模板中的短语的最佳方式是什么?我只想在模板中放入消息键,而不是带有占位符的整个短语。
最佳答案
使用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!
关于java - Velocity 模板 - 消息键而不是带有占位符的整个短语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41504827/