0

我想使用其默认实现运行 Express 3.3.x。Express 使用它的路由模块,那么如果任何路由中的任何视图都可以访问 JS 和 CSS,我该怎么办?

/**
 * Module dependencies.
 */
var express = require('express');
var http = require('http');
var path = require('path');

var piler = require('piler');

var mongoose = require('mongoose');

var config = require('./config');

var app = exports.app = express();
var js =  piler.createJSManager();
var css = piler.createCSSManager();
var srv = require('http').createServer(app);

// all environments
js.bind(app,srv);
css.bind(app,srv);

app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('less-middleware')({ src: __dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));

js.addUrl("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js");

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

/**
 * Routes
 */
var routes = require('./routes');
app.get('/', routes.index);

srv.listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

在堆垛机的例子中:

app.get("/", function(req, res){
    res.render("index.jade", {
        layout: false,
        js: js.renderTags(),
        css: css.renderTags()
    });
});

这行得通。但是我有

app.get('/', routes.index);

那么我必须做什么,js.renderTags() 在每个视图中都有效?

4

1 回答 1

2

如果您尝试将变量传递给渲染,您可以使用res.locals

app.use(function(req,res,next){
  res.locals.layout= false;
  res.locals.js= js.renderTags();
  res.locals.css= css.renderTags();
  next();
});

在你的路由器之前使用它,但不要覆盖你的本地人(res.locals={...}

于 2013-08-28T04:36:11.847 回答