在expressjs渲染中消除布局局部变量
我在nodejs中使用express,并试图保持我的视图渲染干燥。在我的布局中,我有类似以下内容的内容(我正在使用玉)
body
nav.login
-if(currentUser)
="logged in information"
-else
="logged out information"
!=body
问题是每次渲染时,我现在都需要执行
res.render('anything.jade',{
locals: {
currentUser: req.session.currentUser,
/*all of my other locals*/
}
});
所有渲染调用并添加似乎很痛苦然后,如果我必须向布局添加任何其他本地变量,则执行相同的操作。有没有什么方法可以避免在我渲染的每个地方重新输入“currentUser”
I am using express in nodejs, and am trying to keep my view rendering dry. Inside my layout, I have something like the following (I'm using jade)
body
nav.login
-if(currentUser)
="logged in information"
-else
="logged out information"
!=body
The problem is that every time I render, I'm now required to have
res.render('anything.jade',{
locals: {
currentUser: req.session.currentUser,
/*all of my other locals*/
}
});
It seems like a pain to have to go through all of my rendering calls and add that, and then do the same thing if I have to add any other locals to the layout. Is there some way to keep from having to retype 'currentUser' into the locals everywhere I render
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我知道这个答案已经晚了,但对于后代来说:如果您使用的是express,则应该使用提供的动态助手,它们是可查看的辅助函数,以
req,res
作为参数。在您的情况下:这意味着您的视图现在可以调用
#{user}
I know this answer is late, but for posterity: if you're using express, you should use the supplied dynamic helpers, which are view-accessible helper functions which take
req,res
as arguments. In your case:Which means your view could now call
#{user}
我最终做了以下事情:
首先,我设置了一些局部变量
,稍后,我设置了一些局部变量,
我设置了渲染函数,
然后为路由函数
设置了可能有更好的东西,但这是我找到的最佳解决方案,所以远的
I ended up doing the following:
first, I set up some local variables
later, I set some local variables
I set up a render function
then for the routing function
There might be something better, but it's the best solution I've figured out so far
最简单的解决方案是使用返回局部对象的函数。
The easiest solution would be to use a function that returns a locals object.