Monday, April 11, 2011

Locals in ExpressJS

Using Local Variables in Express

ExpressJS allows you to define "locals" which are variables available to the view in multiple places and in multiple ways. Here are a few examples.

// using the res.local syntax
app.all('*', function(req, res, next) {
db.logs.findOne(function(err, logs) {
if (err) return console.log("Error: ", err);
res.local('count', logs.count);
res.local('edit', false);
next();
});
});
// alternatively the res.locals syntax
app.all('*', function(req, res, next) {
db.logs.findOne(function(err, logs) {
if (err) return console.log("Error: ", err);
res.locals({
'count': logs.count,
'edit': false
});
next();
});
});
// finally, as the second argument to a render call
app.get('/reviews/add', function(req, res) {
res.render('view.html', {
review: {
rating: 0,
title: "This is the place.",
article: "This is your review.",
images: [],
slug: "your-url"
}
});
});
// in the first two cases you can confirm which variables
// have been set simply by inspect the _locals variable
console.log("Locals: ", res._locals);

1 comment: