ExpressJS exposing variables and session to Jade templates


Sometimes or should I say most of the time or should I say Always you will need to access variables from your templates no matter whether its Jade templating engine or Smarty (in php) or other MVC framework. You cannot have a working dynamic application if you can’t access variables from your controllers.

In this post I will highlight a couple of points that may help you out when building NodeJS application using ExpressJS and Jade

There are 2 things to consider here

  1. Will the variable be available to all templates
  2. Will the variable be available to one or two templates.

How to deal with

Variable availability to all templates

First technique is to use app.locals

So in your controller or boot js file if you have this object

Then in Jade template you can access above object as

Example template

On the other hand you can also use ExpressJS’s settings object as shown below

Accessing Sessions

I would prefer app.locals over the app.set (this is just me)

With regards to sessions you use sessions by telling express using


This will populate req.session and will have all your session based data.

You can use the technique  below to pass on session variable to your jade views

Make sure that you have above code before this line of code

If you set session property name as shown below

then session property can be accessed like this in Jade template


Passing variables to single template

Now on the other hand if you would like to expose your variable to a view you are rendering here is what you can do to pass on variable to your view

As you can see that we are able to access two variable from our Jade view

  1. path
  2. pageTitle


I hope that this helps. I am pretty sure that this post can be improved with input from you. As a learner I would want that to happen too so that others can benefit from your experience, so please leave your feedback.




Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.