使用中间件自动将变量传递到视图中
在每种请求上寻找一种使用express自动将值传递给视图的方法.
Searching for a way to automatically pass in a value to a view using express on every request.
我在启动脚本中使用了这种中间件,该脚本基本上获得了一组样式表,这些样式表在视图中输出.
I'm using this middleware in my startup script, which basically gets an array of stylesheets which I output in the view.
app.use(function(req, res, next) {
req.styles = helper.getStylesForPage(req.originalUrl);
next();
});
然后我可以在渲染页面时使用它:
I can then use it when rendering the page:
router.get('/', function(req, res, next) {
res.render('index', {
styles: req.styles
});
});
我正在寻找的是一种将该值自动放入传递到视图的对象中的方法,可能是在中间件功能中使用的,因此我不必在每条路线上都手动进行此操作.
What I'm looking for is a way for this value to automatically be put into this object that's passed into the view, possibly in the middleware function so I don't have to manually do it in every route.
我知道了,事实证明我可以使用 res.locals
.我只是将中间件功能切换为:
I figured it out, it turns out I can use res.locals
. I just switched my middleware function to:
app.use(function(req, res, next) {
res.locals.styles = helper.getStylesForPage(req.originalUrl);
next();
});
作为旁注,如果您不知道 res.locals
是什么,则此对象会在您的视图中公开,并且实际上在执行以下操作:
As a sidenote, if you aren't aware what res.locals
is, this object is exposed in your view, and is essentially doing the same thing as this:
router.get('/', function(req, res, next) {
res.render('index', {
styles: helper.getStylesForPage(req.originalUrl)
});
});
唯一的区别是它在可重用的中间件功能中,因此我现在不必将其放在每条路由上.
The only difference is that it's in a re-usable middleware function, so I don't have to put it on every route now.