wesbos
wesbos

Reputation: 26317

Access req and res inside of app.locals

Trying to write some helper methods for an express 3.0 app. Here is an example to greet the user:

  app.locals.greet = function(req,res) {
    return "hey there " + req.user.name;
  }

However, req and res aren't available inside that function. How would I go about writing helpers that I can use inside my jade templates? Am I doing this wrong?

Upvotes: 0

Views: 3423

Answers (3)

Dominic Barnes
Dominic Barnes

Reputation: 28439

You need to add a middleware function/handler that will set those values using the req/res objects before the router calls it's render method. As well, this handler needs to be defined after the information you need to know has been defined. (ie. after session middleware)

// AFTER sessions/auth/etc -- app.use(express.session(...))
app.use(function (req, res) {
    // set any locals using req/res
    res.locals.user = req.user;
    res.locals.greet = function () {
        return "hey there " + req.user.name;
    }
});
// BEFORE router -- app.use(express.router);

See the API documentation on res.locals for further information.

Upvotes: 2

David Weldon
David Weldon

Reputation: 64342

Here are the three parts of a simple example to show how a helper function could use req.locals:

helper function:

app.locals.greet = function(user) {
  return "hey there " + user.name;
}

view template:

h1= greet(user)

render function:

function(req, res) {
  res.render('myview', {user: req.user});
};

If you need more information on setting req.locals, see my answers here and here.

Upvotes: 2

Renato Gama
Renato Gama

Reputation: 16599

Have a look at my config app.js file! that should work to you as the variables will e available at that context.

app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

app.use(connect.compress());
app.use(express.static(__dirname + "/public", { maxAge: 6000000 }));
app.use(express.favicon(__dirname + "/public/img/favicon.ico", { maxAge: 6000000 }));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
    secret: config.sessionSecret,
    maxAge: new Date(Date.now() + (1000 * 60 * 15)),
    store: new MongoStore({ url: config.database.connectionString })
}));
app.use(function(req, res, next){
    console.log("\n~~~~~~~~~~~~~~~~~~~~~~~{   REQUEST   }~~~~~~~~~~~~~~~~~~~~~~~".cyan);
    res.locals.config = config;
    res.locals.session = req.session;
    res.locals.utils = viewUtils;
        res.locals.greet = function(){
                //req and res are available here!
                return "hey there " + req.user.name;
        };
    next();
});
app.use(app.router);
});

Upvotes: 2

Related Questions