Express res.locals.someVariable use in hbs (handlebars template)

帅比萌擦擦* 提交于 2019-12-10 13:18:53

问题


I am trying to pass my session variables to my handlebars templates but am getting stuck. Right now I am using this in my app.configure function:

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

It logs correctly to the console, but when I try to use the "session" variable in my handlebars template, nothing shows up. Here is part of my template:

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

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

        {{> footerPartial}}
</body>

Here is what is being logged by the console:

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

Any ideas?


回答1:


I finally found my solution. It turns out that I was calling this:

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

after

app.use(app.router);

It actually needs to be before the app.router, but after

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


来源:https://stackoverflow.com/questions/16823008/express-res-locals-somevariable-use-in-hbs-handlebars-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!