How can I use a subfolder for my 'views'?
In the main 'app.js' I've set the root folder for the views like so:
app.configure(function(){
app.set('view engine', 'jade');
app.set('views', __dirname + '/apps' );
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/apps' ));
app.use(app.router);
});
And my controller loos like this:
module.exports = function(req, res, base) {
res.render( 'hello/views/');
};
The folder looks like this:
./apps/hello/views/index.js
But still it can't find it. "ERROR: Failed to lookup view "hello/views"
Thanks!
Actually, I made a vastly better solution.
In the app configuration I just set the default view like so:"
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
Later on I inlcude a boot.js (based on the mvc example of expressjs ) in which I include the following:
// allow specifying the view engine
if (obj.engine) app.set('view engine', obj.engine);
app.set('views', __dirname + '/../apps/' + name + '/views');
This will override the view folder to the one specified in the folder 'apps/xxx/views' and will even allow you to specify a new viewtype in the root of that folder like so:
// filename = /apps/hello/index.js
exports.engine = 'jade';
// Render the indexpage
exports.index = function(req, res, next){
res.render('hello');
};
I am surprised that your self answer works, since you should be telling express to render a particular view, and hello/views is a folder. However I'm not familiar with the code pattern you're using for your controller (the base argument is what's throwing me off, since Express middleware uses function(req,res,next).)
My routes look like this:
app.set('views', __dirname + '/apps' );
...
app.get('/hello', function(req,res){
res.render('hello/views/index')
});
In this case ./apps/hello/views/index.jade is a jade file, not a javascript file. If your templates are javascript, perhaps you should set view engine to something other than jade.
You can set views as array of paths
app.set('views', [path.join(__dirname, 'views/users/'), path.join(__dirname, 'views')])
You can check the resulting paths using app.get('views'); which should return an array.
[/server/views/users/, /server/views]
Express will search through the array for available paths. You can then render with just the file name like this
res.render( 'index');
res.render( 'profile');
I fixed this problem by setting the basis view to the root of the directory like so:
app.set('views', __dirname);
And the added the folders from the root on in the controller like so:
res.render( 'apps/hello/views/');
Related
I am using express 4.17.1 combination for my web app.
I am wondering how can i render multiple files depend on the route and multiple folders
Let's say that i have :
When I want to go to the admin path this problem appears :
Passing an array of directory will not work if you're using express version 3 or above. Try the below
app.set('view engine', 'ejs');
var renderer = express.response.render;
express.render = () => {
app.set('views', './regular/viewPath/views');
try {
return renderer.apply(this, arguments);
}
catch (e) {...}
app.set('views', './admin/viewPath/views');
return renderer.apply(this, arguments);
};
const adminRoute = require('./routes/adminFile');
app.use('/admin', adminRoute);
Finally, set the name inside your admin file
router.set('name', 'adminFile');
Other easy alternative would be to put your views in different folders
Example:
views/index.ejs
views/admin/adminFile.ejs
app.set('views', path.join(__dirname, 'views'));
Then on render, you do like
res.render('views/admin/adminFile', configs);
I am trying to learn node.js.
I have the following code.
var express = require('express');
var app = express();
var port = process.env.PORT || 5000;
app.use(express.static('public'));
app.use(express.static('src/views'));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render('index', { title: 'Hello from render', nav: ['Books', 'Author'] });
});
Failed to lookup view "index" in views directory
I have the file named index.ejs. How can I get rid of this error?
Try with
app.set('views', __dirname + '/views');
This is how I fixed it.
app.set('views', './src/views');
app.set('view engine', 'ejs');
I had the same problem too. I have saved the index file as .html file. But it should be index.ejs. then it worked. Check that too
For me it was a banal problem: when I named my 'views' folder, accidentally I typed a white space before the name, so the name was ' veiws', thus, ejs couldn't find the 'views' folder.
i fixed this error by writing below line befor my
app.set('viewengine' , 'ejs')
app.set('views',path.join(__dirname,'views'));
using path is more convenient ,also note to require path befor using it
I had the same issue, then I saved my index file inside the views folder. Now the issue is gone. Also add this line of code in your file
app.set('views', path.join(__dirname, '/views'))
I am using nodejs
i have this code
var someparameter ="teststst";
var fileLocation = path.resolve(__dirname + '/../public/resetpassword.html');
console.log(fileLocation);
res.sendfile(fileLocation);
I want to send someparameter in resetpassword.html
Can anybody tell me how to do this ?
Thanks
You can't. (not without an engine)
Passing parameters to the html won't have any effect (and isnt possible)
You can use a template engine such as jade (or EJS if you want to stay with HTML)
Defined as:
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
And than you can 'render' view with parameters:
app.get('/', function(req, res){
res.render('index', {
users: users,
title: "EJS example",
header: "Some users"
});
});
Usaful Info:
EJS templates
Use EJS to Template Your Node Application
I have server.js file where i define my server and all settings.
And i need to define request url before declaring those settings. Because i need to define them depend on request url.
An example:
var siteDir = ((app.route).lastIndexOf('/admin', 0) === 0) ? '/admin' : '/client';
app.engine('ejs', require('ejs-locals'));
app.set('views', __dirname + ('/template' + siteDir));
app.set('view engine', 'ejs');
So, if request url begins with 'admin' i will load templates from admin folder, otherwise from client.
My current implementation doesn't work, because app.route always returns '/'.
What can i do here. Please give me some advises. Thanks in advanced.
You cannot set the views directory per request with Express, which is what you're trying to do.
But you can use subdirectories in your calls to res.render():
app.get('/admin/', function(req, res) {
res.render('admin/index'); // renders '__dirname + /template/admin/index.ejs'
});
app.get('/', function(req, res) {
res.render('client/index'); // renders '__dirname + /template/client/index.ejs'
});
you can write your own middleware for this.
Something like this:
var siteDir = "/client"; //default case;
app.use(function(req,res,next){
if(req.path == '/admin') siteDir = '/admin';
else siteDir = '/client';
next();
});
app.engine('ejs', require('ejs-locals'));
app.set('views', __dirname + ('/template' + siteDir));
app.set('view engine', 'ejs');
I have a node.js application rendering in ejs 3 template.
let 's say -there is one template, course.ejs, it used to work well in node.js.
res.render('course', locals);
However, today when I tried to change the content, let 's say - course.ejs, it doesn't take effect, there is no error with node.js application and the data passed to the template is all right.
I even copy-pasted the content of this template, and make a new template with a different name - course1.ejs. and change my code to
res.render('course1', locals);
then when the app runs again, it pops up a error saying
Error: Failed to lookup view "course1" template.
The code in node.js and template are all right, it is supposed to work in the ways above. Why it doesn't work now. I have my ejs version 0.8.3, while express in 3.1.0 and node.js in 0.10.0
This is my app configuration.
app.configure(function(){
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
app.set('views',__dirname+'/views');
app.use(express.favicon(__dirname + '/public/favicon.ico'));
app.use(express.compress({
filter: function (req, res) {
return /json|text|javascript|css/.test(res.getHeader('Content-Type'));
},
level: 9
}));
app.use(express.bodyParser({uploadDir:__dirname+'/public/uploads',keepExtensions: true,limit: '50mb'}));
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
cookie: { maxAge: 24 * 60 * 60 * 1000 }
,store: sessionStore
,secret: config.sessionSecret
,key: 'express.sid'
,clear_interval: 3600
}));
app.use(express.csrf());
app.use(function(req, res, next){
res.locals.token = req.session._csrf;
next();
});
app.use(express.static(__dirname+'/public'));
}
my static files is in the public folder, and all the templates are in the view folder.
I wonder has anyone met this kind of problem before
I don't think this configuration can work if your templates have the .ejs extension:
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
Using that configuration, Express will look for TEMPLATENAME.html when you call res.render('TEMPLATENAME', ...), and not TEMPLATENAME.ejs. For that, you need this:
app.engine('ejs', require('ejs').renderFile);
app.set('view engine', 'ejs');
So that's the course1 part solved: Express was looking for course1.html, which it couldn't find, so it would generate the error you got (Failed to lookup view...).
However, I don't see how rendering course.ejs could have worked. Perhaps you have another route which is handling the request you're testing? Or you have a course.html in the views folder (besides the course.ejs)?