How can I turn an EJS template into a string?

TIMEX picture TIMEX · Jul 6, 2011 · Viewed 8.1k times · Source

I want to pass my variables into that template, let it render, and then get the resulting HTML as a string.

How can I do that in Express?

Answer

Lime picture Lime · Jul 6, 2011

Depending on the ejs version the following should work.

var ejs = require('ejs'),
    fs = require('fs'),
    file = fs.readFileSync(__dirname + '/template.ejs', 'ascii'),
    rendered = ejs.render(file, { locals: { items:[1,2,3] } });

console.log(rendered);

You may need to install ejs if it isn't already installed.

cd;npm install ejs