26

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.

1
  • hi did you ever find a better solution to the accepted answer? where the areas don't have to be a sub folder of the views folder? Aug 21, 2015 at 3:51

3 Answers 3

22

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.

6

As a more modular solution, I did something like this in sails.js. Just over-ride the render function for the given request in your middleware. :)

var curRender = res.render;
res.render = function(path, locals, func) {
    var args = [res.locals.explicitPath + '/' + path, locals, func];
    curRender.apply(this, args);
};
0

Full path works too

app.get('/', function(req, res) {
    res.render(path.join(__dirname, 'view.jade'));
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.