Reputation: 10219
In my Express application, I'm able to set app.locals
and use them directly in my templates (rendered using express-handlebars). However, when I set res.locals
in middleware, they are not available unless I pass them in. Am I doing something wrong?
Server
app.locals.foo = "foo";
app.use(function(req, res, next) {
res.locals.bar = "bar";
next();
});
Template
{{foo}} {{bar}}
Test 1
app.get("/", function(req, res) {
app.render("template.html", {}, function(error, html) {
res.send(html);
});
});
Result
foo
Test 2
app.get("/", function(req, res) {
app.render("template.html", {bar: res.locals.bar}, function(error, html) {
res.send(html);
});
});
Result
foo bar
Upvotes: 4
Views: 4244
Reputation: 6998
res.locals
is available in res.render
. I suspect you are calling app.render
by mistake, and should be calling res.render
.
Upvotes: 8
Reputation: 642
The app.locals are available in the entire application as long as the application is up. The res.locals only exists during the request.
Upvotes: 0