我正在使用 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/