node.js - 在 Jade View 中检查 session 变量

标签 node.js express pug passport.js

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

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

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

include menu

在 menu.jade 中,我如何检查用户是否已经登录?我可以检查 jade 中的 session 变量吗?类似下面的 menu.jade 吗?

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

谢谢

最佳答案

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

注意: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

关于node.js - 在 Jade View 中检查 session 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17203828/

相关文章:

node.js - Nodejs 使用加密解密错误最终 block 长度错误

javascript - 如何根据 Express 参数检索 Mongoose 模型

javascript - 通过中间件以express方式访问get请求

javascript - 表达异步发布请求

node.js - 像html文件一样自动渲染jade文件?

json - 警告 "npm WARN saveError ENOENT: no such file or directory"是什么意思?

javascript - 类型错误 : Cannot read property 'loggedIn' of undefined

node.js - 在 Heroku 上存储二进制文件的好方法是什么?

javascript - 无法迭代 mongodb 集合

pug - 将 Jade 变量从内容传递到页面标题?