问题
Going through the peepcode nodejs video and recreating the app on the current express/node versions I've ran into a small issue.
file structure
site
- apps
- - authentication
- - - views
- - - - login.jade
- - - routes.js
- node_modules
- public
- - images
- - javascripts
- - stylesheets
- routes
- views
app.js
login.jade:
extends /views/layout
block content
form(action='/sessions', method='post')
label
| Username
input(type='text', name='user')
label
| Password
input(type='password', name='password')
input(type='submit', name='submit')
app.js
var express = require('express')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', { basedir: process.env.__dirname})
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
require('./apps/authentication/routes')(app)
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
When I navigate to localhost:3000/login
I receive the following error:
Error: /Users/bob/code/site/apps/authentication/views/login.jade:1
> 1| extends /views/layout
2| block content
3| form(action='/sessions', method='post')
4| label
the "basedir" option is required to use "extends" with "absolute" paths
I can update the extends line to: extends ../../../views/layout and make it work, but I'd prefer to know how to set the basedir option.
回答1:
You can use this:
app.locals.basedir = '/your/base/directory';
Or, using the newer Express method,
app.locals.basedir = path.join(__dirname, 'views');
回答2:
In express, you'll notice that there is,
app.set('views', path.join(__dirname, 'views'));
You can just put this line in then,
app.locals.basedir = app.get('views');
Which makes the basedir available to jade.js
so it can resolve absolute paths.
来源:https://stackoverflow.com/questions/16525362/how-do-you-set-jade-basedir-option-in-an-express-app-the-basedir-option-is-r