有没有一种方便的方法可以在 Express 中分几步装饰视图选项?

发布于 2024-11-08 15:40:05 字数 705 浏览 0 评论 0原文

我有一些将在每个动态页面上使用的变量,就像在布局中使用的一样。我们称它们为用户城市。对于 user 我按照明确的指令将中间件放在我使用它的位置前面,除了我这样做:

app.get('/*', function(req, res, next){
  req.user = { name: "Kit" };
  next();
});

user 放在 上似乎是有意义的>req,但它在 cities 上有点崩溃,因为它似乎在语义上不适合 req 对象:

app.get('/*', function(req, res, next){
  User.collection.distinct('city', function(err, response){
    req.cities = response;
    next();
  });
  req.menu = response;
});

然后我遵循:

app.get('/:city', function(req, res){
  res.render('city', {  cities: cities, user: user });
});

是否有更好的方法这?

I have some variables that will be used on every dynamic page, as it's used in the layout. Lets call them user and cities. For user I followed the express instruction to put a middleware infront of where I'd use it, except I did this:

app.get('/*', function(req, res, next){
  req.user = { name: "Kit" };
  next();
});

It seem to make sense to put user on req, but it breaks down a bit on cities as it doesn't seem to semantically fit on the req object:

app.get('/*', function(req, res, next){
  User.collection.distinct('city', function(err, response){
    req.cities = response;
    next();
  });
  req.menu = response;
});

Which I then follow by:

app.get('/:city', function(req, res){
  res.render('city', {  cities: cities, user: user });
});

Is there a better way of going about this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

↙厌世 2024-11-15 15:40:05

我不认为你的做法有什么严重的错误,特别是对于一个小的代码库。看起来城市与用户绑定在一起,因此您可能只想通过在 User.collection 中执行 req.user.cities = response 将城市挂在 req.user 上。不同的回调。另一件事是您在每次请求时都会查询这些城市。这可能没问题,但如果该数据相对静态,则使用会话并在会话生命周期内缓存该数据作为优化是有意义的。

如果您只想有一个更清晰的名称,您可以创建一个顶级 locals 对象,挂起该请求,然后挂起用户和城市,以便 req.locals.cities

I don't see anything horribly wrong with how you're doing it, especially for a small code base. It looks like the cities are tied to the user, so you might just want to hang the cities off of req.user by doing req.user.cities = response in your User.collection.distinct callback. The other thing is that you are querying for these cities on every request. This might be fine, but if that data is relatively static, using sessions and caching that data during the session lifetime would make sense as an optimization.

If you want to just have a clearer name, you can make a top level locals object, hang that off request, and then hang both user and cities off of that so req.locals.cities.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文