我可以编写中间件来影响发送到模板渲染器的数据吗? [英] Can I write middleware to affect the data that is being sent to my template renderer?

查看:54
本文介绍了我可以编写中间件来影响发送到模板渲染器的数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写基于Node.js和Express的Web应用程序,并使用Dust作为模板.我的Dust模板都在单独的文件中使用相同的主版面.现在,在我的应用程序中,一个简单的路由处理程序如下所示:

I'm writing a web application based on Node.js and Express, using Dust for my templates. My Dust templates all use the same master layout in a separate file. Right now a simple route handler in my app looks like this:

app.get('/', function (req, res) {
    res.render('index', {
        tenant: req.tenant
    });        
});

承租人正用于渲染主布局的某些部分.现在,我觉得在每个路由处理程序中将"tenant"变量添加到视图模型中的效率非常低(在开发时).在ASP.NET MVC中,我将编写一个动作过滤器,该动作过滤器在每个动作之后运行,并将租户添加到视图模型中.我可以在Express中做类似的事情吗?写一些连接或路由器中间件?还是res.render立即执行渲染而没有以后修改视图模型的可能性?

The tenant is being used for rendering some parts of the master layout. Now, I feel like it's pretty inefficient (devtime-wise) to add the 'tenant' variable to the view model in every route handler. In ASP.NET MVC I would write an action filter that runs after every action and adds the tenant to the view model. Is there something similar I can do in Express? Write some connect or router middleware? Or does res.render perform the rendering immediately without any possibility to modify the view model lateron?

推荐答案

发布消息两分钟后,IRC上一个不错的小节给了我答案.

And two minutes after posting the message, a nice chap on IRC gives me the answer.

res.locals.tenant = <tenant>

在中间件中完成工作.

这篇关于我可以编写中间件来影响发送到模板渲染器的数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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