ExpressJS 3.0 How to pass res.locals to a jade view?

前端 未结 2 961
温柔的废话
温柔的废话 2020-12-04 16:05

I want to display a flash message after a user fails to sign in but I just can\'t get the variables to show up in my Jade views.

I have some pieces, I know I have t

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 16:37

    Just to give a short summary for everyone who has the same problem and got the impression that is was solved changing res.redirect.

    It is very important to put your app.use middleware before app.router. See the comments by TJ Holowaychuck, the author of express

    • https://groups.google.com/d/msg/express-js/72WPl2UKA2Q/dEndrRj6uhgJ

    Here is an example using a fresh installation of express v3.0.0rc4

    app.js:

    app.use(function(req, res, next){
      res.locals.variable = "some content";
      next();
    })
    
    app.configure(function(){
      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(app.router);
      app.use(express.static(path.join(__dirname, 'public')));
    });
    

    index.jade:

    extends layout
    
    block content
      h1= title
      p Welcome to #{title}
      p= variable
    

提交回复
热议问题