Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Can Express with EJS render HTML to a variable (so I can send as e-mail)?

Can Express with EJS render HTML to a variable (so I can send as e-mail)?

Problem

I am writing a nodejs application that will be sending html e-mail using emailjs. Basically I provide the html to send as a variable that I attach to the message.

Rather than build this variable using lots of string concatenation, I'd like to just render a view using express/ejs and save the contents to the variable.

So instead of doing:

messageHtml = ''+ ....
message.attach({data: messageHtml, alternative: true});

I'd like to do something like:

messageHtml = render('emailTemplate.ejs', viewArgs);
message.attach({data: messageHtml, alternative: true});

Can this be done, and if so, how?!

Problem courtesy of: Zugwalt

Solution

Just require ejs directly and use as per the example, e.g simplified usage (without caching):

var ejs = require('ejs')
  , fs = require('fs')
  , str = fs.readFileSync(__dirname + '/emailTemplate.ejs', 'utf8'); 

var messageHtml = ejs.render(str, viewArgs);

message.attach({data: messageHtml, alternative: true});
Solution courtesy of: Pero P.

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Can Express with EJS render HTML to a variable (so I can send as e-mail)?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×