【问题标题】:Express res.locals.someVariable use in hbs (handlebars template)表达 res.locals.someVariable 在 hbs 中的使用(车把模板)
【发布时间】:2013-05-29 20:13:41
【问题描述】:

我正在尝试将会话变量传递给我的车把模板,但卡住了。现在我在我的 app.configure 函数中使用它:

app.use(function(req, res, next){
        res.locals.session = req.session;
        console.log(res.locals.session);
        next();
});

它正确记录到控制台,但是当我尝试在我的车把模板中使用“会话”变量时,什么都没有显示。这是我的模板的一部分:

<body>
        <nav>
            {{> topBarPartial}}

            {{> secondaryBarPartial}}
        </nav>
        <div>
            <p>before</p>
            {{session}}
            <p>after</p>
            {{> mainPartial}}
        </div>

        {{> footerPartial}}
</body>

这是控制台记录的内容:

{ cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true },
  userId: 45253262,
  name: 'Austin' }

有什么想法吗?

【问题讨论】:

    标签: node.js express handlebars.js


    【解决方案1】:

    我终于找到了我的解决方案。原来我是这么称呼的:

    app.use(function(req, res, next){
            res.locals.session = req.session;
            console.log(res.locals.session);
            next();
    });
    

    之后

    app.use(app.router);
    

    其实需要在app.router之前,但是在之后

    app.use(express.session({
            secret: '***********'
        }));
    

    【讨论】:

    • 是的。在 express 中,你的路由函数在 inside app.router 中间件中执行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    相关资源
    最近更新 更多