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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
Thanks for the quick tip, helped a lot.
ReplyDelete