Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node/Express.js - Overriding where to look for the 'Views' folder for each request

In my Node/Express.js project I can set the views folder globally like so:

app.configure(function() {     app.set('views', __dirname + '/views');     .... snip .... }); 

...and all my view templates go into the views folder.

Is it possible to override where Express looks for views on a request by request basis? For instance, something like the following:

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

The reason I ask is I'm trying to replicate Microsoft ASP.NET MVC's Areas functionality where each Area gets it's own views folder.

like image 774
Sunday Ironfoot Avatar asked Feb 27 '12 18:02

Sunday Ironfoot


People also ask

How do I change the view folder in Express?

You can use the method set() to redefine express's default settings. app. set('views', path. join(__dirname, '/yourViewDirectory'));

What are middlewares in Express?

Middleware literally means anything you put in the middle of one layer of the software and another. Express middleware are functions that execute during the lifecycle of a request to the Express server. Each middleware has access to the HTTP request and response for each route (or path) it's attached to.

How to serve static files in Express js?

ExpressJS Online Training Static files are files that clients download as they are from the server. Create a new directory, public. Express, by default does not allow you to serve static files. You need to enable it using the following built-in middleware.


1 Answers

The 'views' setting is the root directory, so you should be able to specify a sub-folder in the hierarchy:

app.get('/', function(req, res) {     res.render('areaName/viewName'); }); 

It means your 'areas' need to be sub-folders, but it allows you to accomplish the separation you are looking for.

like image 127
Dave Avatar answered Nov 03 '22 20:11

Dave