简体   繁体   中英

velocity template convert into a java string

I want to use Java Mail to send an email but I want to define the content and structure of the mail using a velocity template. Is there any way to make a conversion of the velocity template that yields a String in the way I could use it like this:

String html = velocityConversion_or_whatever();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(html, "text/html");

Thanks.

Velocity can render a template into a StringWriter , so from there it's pretty straightforward to grab the HTML out of your string. Assuming you've already configured your Velocity engine you can do this:

Map data = new HashMap();
// Add data to your map here

StringWriter writer = new StringWriter();
VelocityContext velocityContext = new VelocityContext(data);
velocityEngine.mergeTemplate(templateLocation, velocityContext, writer);
String html = writer.toString();

Velocy有这样的util类:

VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateUrl, model);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM