【问题标题】:Check Session Variable in Jade View在 Jade 视图中检查会话变量
【发布时间】:2013-06-16 17:32:11
【问题描述】:

我正在使用 NodeJS、ExpressJS、PassportJS 和 Jade。

我有一个标题菜单,它将显示登录或注销。如果用户尚未登录,则显示登录,如果用户已经登录,则显示注销。

菜单在单独的jade文件中:menu.jade,并包含在其余的jade文件中。

include menu

在 menu.jade 我如何检查用户是否已经登录?我可以在玉中检查会话变量吗? menu.jade 如下所示?

if ( req.session.name != null)
    a(href='/logout') Logout
else
    a(href='/login') Login  

谢谢

【问题讨论】:

    标签: node.js express pug passport.js


    【解决方案1】:

    您需要向模板公开会话。我这样做的方式是将我的用户变量放入本地:

    注意:req.user 是由passportJS 设置的,你可以在here (in the bottom)看到他们的例子
    注意#2:更多关于本地人here

    app.get('*', function(req, res, next) {
      // put user into res.locals for easy access from templates
      res.locals.user = req.user || null;
    
      next();
    });
    

    然后在模板中你可以这样做:

    - if(_user) {
        div.menuForLoggedInUser
    - } else {
        div.menuForLoggedOutUser
    - }
    

    如果您不想将整个用户对象暴露给模板,请随意将“loggedIn”放入本地并检查...然后是这样的:

    app.get('*', function(req, res, next) {
      // just use boolean for loggedIn
      res.locals.loggedIn = (req.user) ? true : false;
    
      next();
    });
    

    编辑:感谢robertklep 指出 res.locals 与 app.locals

    【讨论】:

    • 我相信您在渲染视图时还需要将 app.locals 实际公开为本地人。 (node.js 和 express 大多避免“魔术”)
    • 我的实现确实有点缺陷。而不是 app.locals = {};它应该是 app.locals({}); (如 expressJS 文档所述)
    • app.locals 是一个应用程序范围的存储,你不应该使用它来存储像req.user 这样的动态数据(因为其他请求可能会覆盖它)。请改用res.locals
    • 我想你写错了,写if(user)而不是if(_user)
    【解决方案2】:

    我会带上这个结果的变量来检查登录。

    // routes/some.js
    exports.index = function (req, res) {
        res.render('somepage', {
            isAlreadyLoggedin: checkSessionSomeway()
        })
    }
    
    // menu.jade
    if ( isAlreadyLoggedin != null)
        a(href='/logout') Logout
    else
        a(href='/login') Login
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 2021-10-09
      相关资源
      最近更新 更多