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

前端 未结 2 962
温柔的废话
温柔的废话 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
    
    0 讨论(0)
  • 2020-12-04 16:58

    If you are using express.session() you must call your function AFTER express.session() but BEFORE app.router, inside of app.configure().

    app.js

    app = express();
    
    app.configure(function(){
      app.set('port', process.env.PORT || 3000);
      app.set('views', __dirname + '/views');
      app.set('view engine', 'jade');
      app.use(express.logger('dev'));
      app.use(express.bodyParser());
      app.use(express.methodOverride());
      app.use(express.session());
    
      // Give Views/Layouts direct access to session data.
      app.use(function(req, res, next){
        res.locals.session = req.session;
        next();
      });
    
      app.use(app.router);
      app.use(express.static(path.join(__dirname, 'public')));
    });
    

    index.jade

    extends layout
    
    block content   
      h1= title   
      p My req.session.var_name is set to #{session.var_name}
    
    0 讨论(0)
提交回复
热议问题