变量在脚本标记中不可用

时间:2022-01-24 23:18:03

I'm using passportjs to do user authentication on my express app. But I've ran into a strange problem:

我正在使用passportjs在我的快递应用程序上进行用户身份验证。但我遇到了一个奇怪的问题:

On my index route I'm rendering the index.jade template with the user parameter

在我的索引路由上,我使用user参数呈现index.jade模板

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

Now in my jade template I have the following

现在在我的玉模板中,我有以下内容

block content
  if user
    h1 logged in #{user}
    script var shared_resources.user = user
  if !user
    h1 Not logged in

For some reason, the conditional pass fine in that user is there. And also when I print out the user object in logged in #{user} it prints out the details fine. However inside the script tag, I'm getting an uncaught reference, user is not defined. Does anyone know why this is happening?

出于某种原因,该用户的条件传递很好。而且当我在登录的#{user}中打印出用户对象时,它会打印出细节。但是在脚本标记内部,我得到了一个未被捕获的引用,用户未定义。有谁知道为什么会这样?

1 个解决方案

#1


2  

You need to use template string in scrip tag as well.

您还需要在脚本标记中使用模板字符串。

script var shared_resources.user = "#{user}"

If you want to embed object you can try following.

如果你想嵌入对象,你可以尝试下面。

script var shared_resources.user = !{JSON.stringify(user).replace(/<\//g, '<\\/')}

#1


2  

You need to use template string in scrip tag as well.

您还需要在脚本标记中使用模板字符串。

script var shared_resources.user = "#{user}"

If you want to embed object you can try following.

如果你想嵌入对象,你可以尝试下面。

script var shared_resources.user = !{JSON.stringify(user).replace(/<\//g, '<\\/')}