使用中间件自动将变量传递到视图中 [英] Pass variable into view automatically using middleware

查看:59
本文介绍了使用中间件自动将变量传递到视图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在每种请求上寻找一种使用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.

这篇关于使用中间件自动将变量传递到视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆