首页 > 解决方案 > 在客户端 js 文件中使用 pug 变量

问题描述

我能够从节点 js 接收变量到 pug,当我在内联脚本中对其进行控制台时,我能够打印数据。但是如何将变量传递给 pug 文件中包含的外部客户端 js 文件

节点js:

res.render(home, {
  title: "home page",
  userId: id 
})

哈巴狗:

body
  -var newId = userId;
script.
  var jsNewId = #{newId}
  console.log("jsNewId",jsNewId)

此 console.log 打印预期的 newid 值。我想将相同的值发送到 pug 文件页脚中包含的 js 文件:

script(src="js/client.js type="text/javascript)

客户端.js

 $(document).ready(function () {
      var jsNewId = #{newId}  //cannot use this syntax 
   })

如何在客户端 js 文件中获取 pug 变量

标签: javascriptnode.jspug

解决方案


为了使用script在外部 javascript 文件中的内联标记中声明的 javascript 变量,您需要将其设为全局变量(不推荐),或使用类似local storage的东西:

在您的 Pug 文件中(请务必在 中缩进您的script标签body

body
  - let newId = userId
  script.
    let jsNewId = #{newId}
    localStorage.setItem('jsNewId', jsNewId)

然后在你的 client.js 文件中:

$(document).ready(function () {
  let jsNewId = localStorage.getItem('jsNewId')
})

最好将您的 client.js 文件作为最后一项包含在 中,body以确保jsNewId在尝试获取它之前存在于本地存储中。


推荐阅读