【问题标题】:I can use app.locals directly in templates but not res.locals我可以直接在模板中使用 app.locals 但不能使用 res.locals
【发布时间】:2016-06-03 03:34:45
【问题描述】:

在我的 Express 应用程序中,我可以设置 app.locals 并直接在我的模板中使用它们(使用 express-handlebars 渲染)。但是,当我在中间件中设置res.locals 时,除非我传入它们,否则它们不可用。我做错了什么吗?

服务器

app.locals.foo = "foo";
app.use(function(req, res, next) {
  res.locals.bar = "bar";
  next();
});

模板

{{foo}} {{bar}}

测试 1

app.get("/", function(req, res) {
  app.render("template.html", {}, function(error, html) {
    res.send(html);
  });
});

结果

foo

测试 2

app.get("/", function(req, res) {
  app.render("template.html", {bar: res.locals.bar}, function(error, html) {
    res.send(html);
  });
});

结果

foo bar

【问题讨论】:

标签: node.js express


【解决方案1】:

只要应用程序启动,app.locals 就在整个应用程序中可用。 res.locals 仅在请求期间存在。

【讨论】:

  • 正确,这就是我在中间件中设置它们的原因。
【解决方案2】:

res.localsres.render 中可用。我怀疑你错误地调用了app.render,应该调用res.render

【讨论】:

  • 就是这样!我没有意识到使用 app.renderres.render 之间有区别。
猜你喜欢
  • 1970-01-01
  • 2015-09-20
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多