根据调用 res.render()的文件的位置更改 Express 视图文件夹

当我调用 res.render ()时,我想要更改 Express 的视图文件夹。

例如,如果我在/file/file.js 中调用 res.render (viewName) ,我希望 Express 查找/file/views 中的视图。

如果文件在/folder1/folder2/file.js 中,我希望 Express 查找/folder1/folder2/views 中的视图

有可能吗?

104240 次浏览

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

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

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);

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

Simple example:

app.get('/your/path', function(req, res) {
//viewname can include or omit the filename extension
res.render(__dirname + '/folder/with/views/viewname');
});​​​​​​​​​​

That's pretty simple

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

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

This changes the path where Express would search for specified views.

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

(Sorry I can't comment yet)

@nuzzolilo's answer works well. But if you prefer ES6

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

This simply improves code readability ;)

Set the path of view location.

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

Set the view engine.

app.set('view engine','ejs');

Complete code will look like below.

const express = require('express');
const path = require('path');


const app = express();


app.set('views', path.join(__dirname, '/views'));
app.set('view engine','ejs');


app.listen(3000, () => console.log('Application is running on'));