【问题标题】:Pug Express req.user InterpolationPug Express req.user 插值
【发布时间】:2018-02-18 06:00:02
【问题描述】:

我很难从 Express 访问 Pug 中的变量。

我的路线如下:

router.get('/', ensureAuthenticated, function(req, res, next) {
  res.render('profile/profile', {user: req.user});
});

我的模板看起来像:

          .card
            .card-body
              h4.card-title Local Profile
              if (user)
                p.card-text
                  strong.pr-2 ID: !{user.userEmail}
                  br
                  br
                  strong.pr-2 Name:
                  = user
                  br
                  br
                  strong.pr-2 Email:
                  = user
                  br
                  br
                  strong.pr-2 Password:
                  span.text-muted= user
                  a.btn.btn-default(href="/profile/edit") Edit
                p.card-text
                small.text-muted Last login
                = user

用户对象看起来像:

{UID: 5, userEmail: "rtester@testing.com", userPassword: "bd4eb56b41fc3663dfe2761ff34621a544ecfe27", userLastLogin: "2017-11-20T22:18:13.000Z", userToken: "cae45ae7e68ef8024d4ad5b56c68f263"}

如果我只包含用户而不进行字符串化,那么我会得到 Object 对象。如果我字符串化,我可以输出对象,但尝试访问对象中的属性什么也得不到。

但是如果我

console.log(x.userEmail) 

之后

var x = !{JSON.stringify(user)} 

然后我得到了财产。

任何帮助都会很棒!

【问题讨论】:

    标签: node.js express pug


    【解决方案1】:

    使用user.userEmail 而不是!{user.userEmail} 这对我来说很好,

    app.get('/', function(req, res, next) {
        var u = {UID: 5, userEmail: "rtester@testing.com", userPassword: "bd4eb56b41fc3663dfe2761ff34621a544ecfe27", userLastLogin: "2017-11-20T22:18:13.000Z", userToken: "cae45ae7e68ef8024d4ad5b56c68f263"}
      res.render('index', { user: u });
    });
    

    ,

    html
      head
        title= user.userEmail
      body
        h1= user.userEmail
    

    【讨论】:

    • 试过了,没用。只是空白处。没有错误,它没有渲染到视图中。
    • 直接使用 user.userEmail 为我工作,没有 !{}
    • 感谢您的帮助。问题实际上是护照和会议。正在创建的 req.user 对象有一个嵌套属性,当直接传递给视图时,其中有其他“东西”,我在向浏览器执行 console.log 时看不到并且没有显示,但我可以看到在后端。我发现这个问题很有帮助。 stackoverflow.com/questions/40670322/…
    【解决方案2】:

    这个问题实际上与 Pug 或 Express 无关。这是 Passport 在使用 Bookshelf.js 找到用户后设置 req.user 变量的方式。

    对象中有一些额外的嵌套属性。这个单独的答案使我找到了一个解决方案来隔离我需要的信息。 Cannot get properties of req.user

    在 Pug 中访问信息的方式与文档中列出的相同。

    【讨论】:

      猜你喜欢
      • 2020-10-08
      • 2016-08-07
      • 2016-04-01
      • 2020-01-14
      • 2020-08-31
      • 2017-12-02
      • 2014-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多