Point name file Express.js res.render

How to use a file named dot on res.render() in express.js? For instance,

There is a template file called view.sample.ejs , I want to display it

 app.get('/sample', function(req, res){ res.render('view.sample'); }) 

The result is

 Error: Cannot find module 'sample' 

How to use dots?

(a plus)

I want to name the following mvc model, for example

 sample.model.js sample.controller.js sample.view.ejs sample.view.update.ejs ... 

There is no problem with the js file, but I could not make the ejs file.

+5
source share
1 answer

If we look at the node_modules/express/lib/view.js , we find that the design of the template path all after the node_modules/express/lib/view.js in the file name should 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 appropriate file extension mechanism, you will create 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'); }) 
+5
source

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


All Articles