全局设置dynamic帕格variables

我正在使用express和pug,有一些值我想传递给每个请求哈巴狗,例如: req.sessionreq.path 。 每次render()这些值传递给render()方法似乎太多了。

所以不要这样做:

 app.get('/', (req, res) => { res.render('home', {session: req.session}) }) app.get('/profile', (req, res) => { res.render('profile', {session: req.session}) }) 

添加的路线越多,需要pipe理的项目就越多。 有没有一种全球性的方式,我可以设置他们一次比app.locals所以他们是唯一的每个请求?

您可以使用一些自定义中间件和locals来为每个请求中的每个模板设置可用的variables。 同样的方法适用于Express可以使用的所有模板系统,而​​不仅仅是Pug。

把下面的路线之前

 app.use((req, res, next) => { res.locals.session = req.session next() }) 

然后在你的模板中,你可以这样称呼它。

 h3= session.name