Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Express Middleware to populate a Jade variable for all app.get()'s

Express Middleware to populate a Jade variable for all app.get()'s

Problem

I have a Jade file that all of my Templates extend called layout.jade. In it I want to be able to have a logout button if the user is currently logged in (this is kept track of in req.session).

So layout.jade will have something like,

-if (loggedin)
  a.navButton(href="/logout") Log Out

The route for a page would look something like,

app.get("/foo", function(req, res) {
    res.render("foo", {loggedin: req.session.isValidUser});
});

The thing is, I don't want to have to populate the loggedin variable manually in every single route. Is there a way I can use Express Middleware to automatically set some default options for the object sent to res.render? Or is there a better method to do this?

Basically I'm asking how I can have some set of variables always sent to templates, as well as the ability to have certain custom variables available in certain templates by manually setting them in the routes.

Problem courtesy of: PherricOxide

Solution

It seems this is actually a documented feature I just had trouble finding, unless anyone has a better way of doing it; From the latest Express documentation,

app.locals: Application local variables are provided to all templates rendered within the application. This is useful for providing helper functions to templates, as well as app-level data.

So in my login success function has,

req.session.username = profile.username;
app.locals.username = profile.username;

My logout function,

app.get('/logout', function (req, res) {
    delete app.locals.username;
    req.session.destroy();
    res.redirect('/login');
});

And finally in layout.jade/all of my templates,

- if(username)
  a.navButton(href="/logout") Logout
Solution courtesy of: PherricOxide

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Express Middleware to populate a Jade variable for all app.get()'s

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×