Search code examples
node.jsexpressnunjucks

How can I fill my template with default data in nunjucks and express.js


I'm using nunjucks as my template engine in an express application. I'm searching for a good way to populate the template with data about state of login.

I don't want to put it in the template at every function call i make.

I have following middleware:

module.exports = function(req, res, next){
    let session = req.session;
    req.extras = req.extras || {};
    req.extras.login = session.login || false;;
    req.extras.currentUser = session.currentUser || null;
    next();
};

I'm searching for a way to just have this:

app.get("/",function(req, res){
   res.render();
})

And i want to be able to use "login" and "currentUser" in template.


Solution

  • The solution was to put the data to res.locals

    The middleware should look like this:

    module.exports = function(req, res, next){
        let session = req.session;
        res.locals.login = session.login || false;;
        res.locals.currentUser = session.currentUser || null;
        next();
    };