Node.js - 设置默认局部变量以传递到布局/模板中

发布于 2024-12-24 18:52:17 字数 159 浏览 3 评论 0原文

我正在使用 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 技术交流群。

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

发布评论

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

评论(1

国产ˉ祖宗 2024-12-31 18:52:17

您可以通过定义动态视图助手来实现此目的,如官方 Express 指南 中指出的:

app.dynamicHelpers({
  session: function(req, res){
    return req.session;
  }
});

然后在您的视图中您可以简单地访问session 变量,例如用于显示用户的 session.user。

You can achieve this by defining a dynamic view helper, as pointed out in the official Express guide:

app.dynamicHelpers({
  session: function(req, res){
    return req.session;
  }
});

Then in your views you can simply access the session variable, and for example session.user to display the user.

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