Reputation: 26317
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
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
Reputation: 64342
Here are the three parts of a simple example to show how a helper function could use req.locals
:
app.locals.greet = function(user) {
return "hey there " + user.name;
}
h1= greet(user)
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
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