Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js res.render dot name file

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.

like image 884
ton1 Avatar asked Mar 06 '16 01:03

ton1


People also ask

What does res render () function do?

The res. render() function is used to render a view and sends the rendered HTML string to the client.

What is Express JSON ()?

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.

Does Res send end the function?

send doesn't return the function, but does close the connection / end the request.

What is RES locals in Express?

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.


1 Answers

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');
})
like image 107
stdob-- Avatar answered Sep 28 '22 03:09

stdob--