设置速度模板
我最终使用这个问题来解决我设置模板路径的问题。我正在使用速度模板化 html 电子邮件。
您可以使用以下几种方法来说明如何设置模板路径。它将属性“file.resource.loader.path”设置为绝对路径。我为模板创建了一个目录,然后右键单击模板文件以获取完整路径(在 Eclipse 中)。您使用该完整路径作为 file.resource.loader.path 属性的值。我还添加了“runtime.log.logsystem.class”属性并设置它,因为我收到了抱怨日志记录的异常。
实用速度方法
public static VelocityEngine getVelocityEngine(){
VelocityEngine ve = new VelocityEngine();
Properties props = new Properties();
// THIS PATH CAN BE HARDCODED BUT IDEALLY YOUD GET IT FROM A PROPERTIES FILE
String path = "/absolute/path/to/templates/dir/on/your/machine";
props.put("file.resource.loader.path", path);
props.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");
ve.init(props);
return ve;
}
public static String getHtmlByTemplateAndContext(String templateName, VelocityContext context){
VelocityEngine ve = getVelocityEngine();
Template template = ve.getTemplate(templateName);
StringWriter writer = new StringWriter();
template.merge(context, writer );
System.out.println( writer.toString());
String velocityHtml = writer.toString();
return velocityHtml;
}
如何使用上述代码,创建一个速度上下文以提供给实用程序方法
以下是您可以使用上述方法的方法。您只需指定模板文件的文件名,并创建一个简单的VelocityContext 上下文来存储您的模板变量。
VelocityContext context = new VelocityContext();
context.put("lastName", "Mavis");
context.put("firstName", "Roger");
context.put("email", "mrRogers@wmail.com");
context.put("title", "Mr.");
String html = VelocityUtil.getHtmlByTemplateAndContext("email_template_2015_10_09.vm", context);
示例模板 HTML
可以像这样访问变量(在我的情况下保存在文件email_template_2015_10_09.vm中):
<p> Hello $firstName $lastName </p>