Express.js中模板读取挂在resp上的值

只需要把ejs模板中读取的值挂在res.locals上,在ejs模板中就可以访问到,例如下面的内容

res.locals.seoLang = {
    keywords: "keyword1, keyword2",
    description: "This is a description"
};

在ejs中读取,如果要实现多语言,就可以判断语言环境在res.locals上对应字段设置对应的语言文案

<meta name="keywords" content="<%=seoLang.keywords%>" />  
<meta name="description" content="<%=seoLang.description%>" />

官方文档说明: https://expressjs.com/en/4x/api.html#res.locals

res.locals 使用说明

Use this property to set variables accessible in templates rendered with res.render. The variables set on res.locals are available within a single request-response cycle, and will not be shared between requests.

The locals object is used by view engines to render a response. The object keys may be particularly sensitive and should not contain user-controlled input, as it may affect the operation of the view engine or provide a path to cross-site scripting. Consult the documentation for the used view engine for additional considerations.

In order to keep local variables for use in template rendering between requests, use app.locals instead.

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on to templates rendered within the application.

app.use(function (req, res, next) {
  // Make `user` and `authenticated` available in templates
  res.locals.user = req.user
  res.locals.authenticated = !req.user.anonymous
  next()
})

留下回复