Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can use app.locals directly in templates but not res.locals

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
like image 578
David Jones Avatar asked Feb 07 '23 16:02

David Jones


1 Answers

res.locals is available in res.render. I suspect you are calling app.render by mistake, and should be calling res.render.

like image 192
bolav Avatar answered Feb 12 '23 10:02

bolav