如何在我的控制器中将变量用作全局变量?

huangapple go评论100阅读模式
英文:

How can I use a variable as global in my controller?

问题

我想在每个视图中使用一个名为"user"的变量,我认为解决这个问题的方法是从控制器共享变量到视图,但我有20个视图,所以我不想在控制器的每个方法中都添加20次这个变量。例如,这里我正在将变量"user"共享到视图"profile",但我希望在所有视图中使用这个变量:

profile: (req, res) => {
    if (req.session.user) {
        res.render("profile", { user: req.session.user })
    } else {
        res.render("login")
    }
}
英文:

I want to use a variable called "user" in every view, i think a way to solve this is to shared the variable from the controler to the views, but I have 20 views, so I don't want to add 20 times the variable in every method of my controller. For example, here I'm sharing the variable user, to the view profile, but I want to use this variable in all views:

profile: (req,res) => {
 if (req.session.user) {
      res.render("profile",{user:req.session.user})
 }
 else{
      res.render("login")
 }
}

答案1

得分: 0

这是res.locals的作用。模板引擎会自动搜索res.locals中你在模板中引用的任何变量,因此,如果你将它放在那里,那么你就不必在每次res.render()调用时手动传递它。

因此,你可以创建一个在控制器路由之前定义的中间件,就像这样:

app.use((req, res, next) => {
    if (req.session.user) {
        res.locals.user = req.session.user;
        next();
    } else {
        res.redirect("/login");
    }
});

然后,你的控制器端点可以像这样简化:

profile: (req, res) => {
   res.render("profile");
}

如果req.session.user存在,它将把user对象放入res.locals,模板只需引用user,模板引擎会为你找到它(就像你将其传递给res.render()一样)。

如果req.session.user不存在,那么中间件将重定向到/login。这通常比为实际上是您的个人资料URL的URL呈现登录页面要好。呈现的内容应与URL匹配。

英文:

This is what res.locals is for. Template engines will automatically search res.locals for any variable that you reference in your template so if you put it there, then you don't have to pass it manually to every res.render() call.

So, you could make middleware that is defined before your controller routing like this:

app.use((req, res, next) => {
    if (req.session.user) {
        res.locals.user = req.session.user;
        next();
    } else {
        res.redirect("/login");
    }
});

Then, your controller endpoint can just be this:

profile: (req,res) => {
   res.render("profile");
}

If req.session.user exists, it will put the user object into res.locals where the template can just reference user and the template engine will find it for you (just the same as if you passed it to res.render().

If req.session.user does not exist, then the middleware will redirect to /login. This is generally better than rendering the login page for a URL that is actually your profile URL. The rendered content should match the URL.

huangapple
  • 本文由 发表于 2023年3月7日 08:45:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75657110.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定