Accessing Express.js req or session from Jade template

Viewed 30193

I am wondering if there is an easy way to access Express.js' req or session variables from within a Jade template without passing it in through the normal response.

Or is this the only way?

res.render('/', {
    session: req.session
});
8 Answers

You could solve this with a render function in which you use to render every view that needs the session variable as a local variable accessible in the template(usually when a user is logged in for example).

Here is an example of a function but you can adjust as you like:

var renderView = function(res, template, context, session, cb) {
    context.session = session;

    if(cb){
        res.render(template, context, function(error, html){
            cb(error, html)
        }
    } else {
        res.render(template, context)
    }
}

Then it can be used like this:

app.get("/url", function(req, res){

    req.session.user_email = user_email;

    renderView(res, "template_name", { local_variables: local_variables }, req.session)
});

and in your jade template you can access the session variables like this:

div.user-email #{session.user_email}

If your session object variable is declared globally then In global

var sess

In function

sess=req.session

req.render('index.pug',{sess})

Related