Node.js - 设置默认局部变量以传递到布局/模板中
我正在使用 Node.js 和 Express,并且我想将局部变量传递到每个页面的布局中,有什么方法可以做到这一点吗?我使用 Jade 作为我的模板引擎。
我想要这个的原因是因为我想在每个页面上显示用户的用户名(使用会话),除了每次都将其包含在本地对象中之外,还有什么方法可以做到这一点?
I'm using Node.js and Express, and I want to pass a local variable in to the layout on every page, is there any way to do this? I'm using Jade as my templating engine.
The reason I want this is because I want to display the user's username on every page (using session), any way to do this other than including it every time in the local object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过定义动态视图助手来实现此目的,如官方 Express 指南 中指出的:
然后在您的视图中您可以简单地访问
session
变量,例如用于显示用户的 session.user。You can achieve this by defining a dynamic view helper, as pointed out in the official Express guide:
Then in your views you can simply access the
session
variable, and for example session.user to display the user.