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
res.locals is available in res.render. I suspect you are calling app.render by mistake, and should be calling res.render.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With