Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?!

like image 981
Aaron Silverman Avatar asked Apr 02 '12 01:04

Aaron Silverman


People also ask

How do you render a variable in EJS?

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.

Can I use HTML in EJS?

EJS is a simple templating language that lets you generate HTML markup with plain JavaScript.

How do I convert HTML to EJS?

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.


1 Answers

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});
like image 180
Pero P. Avatar answered Sep 28 '22 09:09

Pero P.