Change Express browse folder based on where the file that res.render () is called

I would like to change the Express view folder when I call res.render ().

For example, if I call res.render (viewName) inside /folder/file.js, I would like Express to look at the view inside / folder / views.

If the file is inside / folder 1 / folder2 / file.js, I would like this Express to look for the view inside / folder 1 / folder2 / views

Is it possible?

+62
express
Feb 19 '14 at 15:43
source share
5 answers

You can use the set() method to override express defaults.

 app.set('views', path.join(__dirname, '/yourViewDirectory')); 

To dynamically change the path, you can do something like this:

 var express = require('express'); var path = require('path'); var app = express(); app.engine('jade', require('jade').__express); app.set('view engine','jade'); app.customRender = function (root,name,fn) { var engines = app.engines; var cache = app.cache; view = cache[root+'-'+name]; if (!view) { view = new (app.get('view'))(name, { defaultEngine: app.get('view engine'), root: root, engines: engines }); if (!view.path) { var err = new Error('Failed to lookup view "' + name + '" in views directory "' + root + '"'); err.view = view; return fn(err); } cache[root+'-'+name] = view; } try { view.render(opts, fn); } catch (err) { fn(err); } } app.get('/', function(req, res) { app.customRender(path.join(__dirname, '/path/to/user/'),'index',function (err,html) { if (err) res.send(404); else res.send(200,html); }); }); app.listen(3000); 
+98
Feb 19 '14 at 16:06
source share

Instead of simply passing the name of your view to a rendering function, you can pass a relative or absolute path.

A simple example:

 app.get('/your/path', function(req, res) { //viewname can include or omit the filename extension res.render(__dirname + '/folder/with/views/viewname'); });​​​​​​​​​​ 
+46
Dec 09 '15 at 5:45
source share

It is pretty simple

to change the Express view folder when you call res.render (), just set the path where the views are located, in your case

 app.set('views','./folder1/folder2/views'); 

This changes the way in which Express will look for the specified views.

+5
May 5 '16 at 12:03
source share

(Sorry I can not comment yet)

@nuzzolilo answer works well. But if you prefer ES6

 app.get('/path', function (req, res) { res.render(`${__dirname}/templates_dir/index`, { data: "value" }); }); 

It just improves the readability of the code;)

+3
Jun 15 '17 at 22:55
source share

You can also get the relative path using require.resolve : res.render(require.resolve('./folder/with/views/viewname'));

+2
May 17 '16 at 21:34
source share



All Articles