你如何在快递应用程序中设置基于jade的选项? (“extendsir”选项需要使用“extends”和“绝对”路径)

时间:2013-05-13 15:08:55

标签: node.js express pug

通过peepcode nodejs视频并在当前快递/节点版本上重新创建应用程序我遇到了一个小问题。

文件结构

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

当我导航到localhost:3000/login时,收到以下错误:

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

我可以将extends行更新为:extends ../../../views/layout并使其正常工作,但我更愿意知道如何设置basedir选项。

2 个答案:

答案 0 :(得分:24)

您可以使用:

app.locals.basedir = '/your/base/directory';

或者,使用较新的Express方法,

app.locals.basedir = path.join(__dirname, 'views');

答案 1 :(得分:8)

在快递中,你会发现有,

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

你可以把这一行放在那里,

app.locals.basedir = app.get('views');

这使得基础可用于jade.js,因此它可以解析绝对路径。