Use res.render()
.
If you’re already using Express to render views you shouldn’t need to use EJS directly. Just make sure you have it listed as a dependency in your package.json
and Express will take care of the rest!
Here’s some more details:
Calling ejs.render()
or ejs.renderFile()
bypasses the Express view engine. Really all that means is you have to provide absolute paths to EJS and you have to send the rendered HTML to the client.
This:
app.get('/', function (req, res) {
res.render('index.ejs');
});
Is equivalent to this:
app.get('/', function (req, res) {
res.send(ejs.renderFile(__dirname + '/views/index.ejs'));
});
The callback parameter in res.render()
is there to support view engines that need to return asynchronously. EJS uses fs.readFileSync
to render its templates so ejs.render()
and ejs.renderFile()
don’t require a callback—they just return the rendered HTML.
The one scenario I can think of where you might use EJS directly is if you want to “compile” a template into a function that you can call later:
var ejs = require('ejs'),
read = require('fs').readFileSync;
var template = ejs.compile(read('path/to/template.ejs', 'utf-8'));
console.log(template());