Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 243
anonymousfox Avatar asked May 29 '13 20:05

anonymousfox


People also ask

What is the use of express handlebars?

Fast execution. Handlebars compiles templates into JavaScript functions. This makes the template execution faster than most other template engines.

Is handlebars a template language?

Handlebars is a simple templating language. It uses a template and an input object to generate HTML or other text formats. Handlebars templates look like regular text with embedded Handlebars expressions.

How do I compile handlebars templates?

Getting started Next, install the Handlebars npm package, which contains the precompiler. Create a file name example. handlebars containing your template: Handlebars <b>{{doesWhat}}</b> precompiled!


1 Answers

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: '***********'
    }));
like image 62
anonymousfox Avatar answered Oct 02 '22 11:10

anonymousfox