Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

If the file is inside /folder1/folder2/file.js, I would like that Express look for the view inside /folder1/folder2/views

Is it possible ?

like image 526
Talysson Avatar asked Feb 19 '14 15:02

Talysson


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 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 render in Express?

render() method is used for returning the rendered HTML of a view using the callback function. This method accepts an optional parameter that is an object which contains the local variables for the view. This method is similar to the res.


Video Answer


1 Answers

You can use the method set() to redefine express's default settings.

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

For a dynamic path change 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); 
like image 91
Pedro Nasser Avatar answered Sep 29 '22 16:09

Pedro Nasser