How can I use dot named file on res.render()
in express.js?
For instance,
There is template file named view.sample.ejs
, I want to render it
app.get('/sample', function(req, res){
res.render('view.sample');
})
The result is,
Error: Cannot find module 'sample'
How can I use dots?
(plus)
I want to name follow mvc model, like
sample.model.js
sample.controller.js
sample.view.ejs
sample.view.update.ejs ...
No problem js file, but render ejs file I couldn't.
The res. render() function is used to render a view and sends the rendered HTML string to the client.
json() is a built-in middleware function in Express. This method is used to parse the incoming requests with JSON payloads and is based upon the bodyparser. This method returns the middleware that only parses JSON and only looks at the requests where the content-type header matches the type option.
send doesn't return the function, but does close the connection / end the request.
The res. locals is an object that contains the local variables for the response which are scoped to the request only and therefore just available for the views rendered during that request or response cycle.
If we look at the library node_modules/express/lib/view.js
, we find that the design of the path to the template everything after the dot in the file name shall be considered as an extension:
this.ext = extname(name); // 'view.sample' => '.sample'
this.name = name; // 'view.sample' => 'view.sample'
And when we try to load the corresponding file extension engine will generate an error:
if (!opts.engines[this.ext]) { // '.sample' engine not found
// try load engine and throw error
opts.engines[this.ext] = require(this.ext.substr(1)).__express;
}
Ok, what to do? Just add the extension:
app.get('/sample', function(req, res){
res.render('view.sample.ejs');
})
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