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 = '<html>'+ ....
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?!
To render a variable as HTML in EJS, we can use various tags. to run code code which is evaluated but not printed. to evaluate and print out code as an escaped string. to evaluate and print out code as is.
EJS is a simple templating language that lets you generate HTML markup with plain JavaScript.
Converting Static Pages to EJS FilesIn the root directory of your website, create a folder called views and inside that folder create two sub-folders called pages and partials. Move all your HTML files into the pages sub-folder and rename the . html file extensions to . ejs.
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With