What is the difference between res.render () and ejs.render () in Node.js and an Express app

I use the EJS template engine in my Node.js and Express application, and so far have used its functionality and rendering, and so far there have been no problems.

However, although I have always used the syntax res.render(filename, options, callback)in my server program to render the contents of the file, I wonder what the difference is between res.render()and ejs.render().

Both methods seem to take the render file name as the first argument and Object to insert into the file as the second argument (e.g. {title: "title here"}). res.render()can take a callback function as the third (optional) argument, and I used it whenever I want to use nested rendering, but from the documentation of the EJS Github repository it may not be able to accept the callback, again, at least the documentation in the repository Github does not accept the argument (although in any case its argument will be optional).

So, I wonder what the difference is between res.render()and ejs.render(). If only it res.render()can take a third argument, what is the point of use ejs.render()? Or is there anything that ejs.render()can use that res.render()cannot? In general, what function should I use in my application?

I am writing app.set('view engine', 'ejs');to use EJS in my application for your information.

+4
source share
2 answers

Use res.render().

If you are already using Express to view presentations, you do not need to use EJS directly. Just make sure that you specify the dependency in your own package.json, and Express will take care of the rest!

:

ejs.render() ejs.renderFile() Express. , EJS, HTML .

:

app.get('/', function (req, res) {
  res.render('index.ejs');
});

:

app.get('/', function (req, res) {
  res.send(ejs.renderFile(__dirname + '/views/index.ejs'));
});

res.render() , . EJS fs.readFileSync , ejs.render() ejs.renderFile() - HTML.

, EJS , "" , :

var ejs = require('ejs'),
    read = require('fs').readFileSync;

var template = ejs.compile(read('path/to/template.ejs', 'utf-8'));

console.log(template());
+14

, ejs. , res. , html-. , ejs.render(), . , ejs.render() res.render().

+3

Source: https://habr.com/ru/post/1535434/


All Articles