# res.locals

使用此属性设置在使用 res.render 呈现的模板中可访问的变量。

# 概要

res.locals

# 描述

使用此属性设置在使用 res.render 呈现的模板中可访问的变量。res.locals 上设置的变量在单个请求-响应周期内可用,并且不会在请求之间共享。

为了保留局部变量以用于请求之间的模板渲染,请改用 app.locals

此属性对于向应用程序中呈现的模板公开请求级信息(例如请求路径名称、经过身份验证的用户、用户设置等)很有用。

app.use((req, res, next) => {
  // Make `user` and `authenticated` available in templates
  res.locals.user = req.user
  res.locals.authenticated = !req.user.anonymous
  next()
})
Last Updated: 3/22/2023, 7:27:28 PM