I use EJS template engine in my Node.js and Express app, and have used its functionality and rendering so far, and haven't had any problems so far.
However, while I always used the syntax res.render(filename, options, callback)
in my server-side program to render the contents of the file, I wonder what's the difference between res.render()
and ejs.render()
.
It looks like both methods take a rendering filename as a first argument and Object to embed to the file as a second argument (like {title: "title here"}
). res.render()
can take a callback function as a third (optional) argument and I've used it whenever I want to make use of a nested rendering, but from the documentation of the EJS Github repository, it might not be able to take the callback function, again at least the documentation at the Github repository doesn't take the argument (though its argument would be optional anyway).
So I wonder, what's the difference between res.render()
and ejs.render()
. If only res.render()
can take the third argument, what's the point of using ejs.render()
? Or is there anything that ejs.render()
can use that res.render()
cannot? And in general which function should I use in my app?
I write the app.set('view engine', 'ejs');
to use EJS in my app for your information.
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());
This was a bit of info for me as i'm not familiar with ejs
. But I have encountered a scenario where I don't have res
variable. For instance I need to send a email with a html template. So in this use case, I found that we can only ejs.render()
to use the template to email. Hence, ejs.render()
is important as res.render()
.
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