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

Node.js - Set default local variables to pass into layout/template

Node.js - Set default local variables to pass into layout/template

Problem

I'm using Node.js and Express, and I want to pass a local variable in to the layout on every page, is there any way to do this? I'm using Jade as my templating engine.

The reason I want this is because I want to display the user's username on every page (using session), any way to do this other than including it every time in the local object?

Problem courtesy of: Varun Singh

Solution

You can achieve this by defining a dynamic view helper, as pointed out in the official Express guide:

app.dynamicHelpers({
  session: function(req, res){
    return req.session;
  }
});

Then in your views you can simply access the session variable, and for example session.user to display the user.

Solution courtesy of: alessioalex

Discussion

View additional discussion.



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

Share the post

Node.js - Set default local variables to pass into layout/template

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×