DRYing up layout locals in expressjs rendering

By : Ryan
Source: Stackoverflow.com
Question!

I am using express in nodejs, and am trying to keep my view rendering dry. Inside my layout, I have something like the following (I'm using jade)

body
  nav.login
    -if(currentUser)
      ="logged in information"
    -else
      ="logged out information"
  !=body

The problem is that every time I render, I'm now required to have

res.render('anything.jade',{
  locals: {
    currentUser: req.session.currentUser,
    /*all of my other locals*/
  }
});

It seems like a pain to have to go through all of my rendering calls and add that, and then do the same thing if I have to add any other locals to the layout. Is there some way to keep from having to retype 'currentUser' into the locals everywhere I render

By : Ryan


Answers

The easiest solution would be to use a function that returns a locals object.

function(req) {
    return {
        currentUser: req.session.currentUser,
        /*all of my other locals*/
    };
}

res.render('anything.jade',{
  locals: defaultLocals(req)
});


I ended up doing the following:

first, I set up some local variables

app.use(function(req,res,next){
  req.localvars = new Object;
  next();
});

later, I set some local variables

app.use(function(req,res,next){
  req.localvars.currentUser = req.session.currentUser;
  next();
});

I set up a render function

function renderer(file){  
  return function(req,res,next){
    res.render(file,{locals:req.localvars});
  }
}

then for the routing function

app.get('/',blah,blah,whatever,setSomeMoreLocalsHere,renderer(index.jade));

There might be something better, but it's the best solution I've figured out so far

By : Ryan


This video can help you solving your question :)
By: admin