[英]How to pass a Pug JSON object to client side JavaScript
I am trying to pass a JSON object from pug to client side JavaScript. 我试图将JSON对象从pug传递到客户端JavaScript。 Here's how the code is structured. 这是代码的结构。 I render a JSON object and pass it to Pug from my Node-Express backend. 我呈现一个JSON对象,并将其从Node-Express后端传递给Pug。 Code below: 代码如下:
server.js
: server.js
:
app.get('/myrooms', function(req, res) {
Room.find()
.where('_id')
.in(user.rooms)
.exec(function (err, records) {
res.render('rooms/index', {myrooms : records})
})
})
After that this object is available in my pug file. 之后,该对象在我的pug文件中可用。 Now I want to pass it to a client side script. 现在,我想将其传递给客户端脚本。 I am doing something like this in my index.pug
file. 我在index.pug
文件中正在做类似的事情。
index.pug
: index.pug
:
script(src='/js/play.js').
trooms = "#{myrooms}"
play.js
: play.js
:
console.log(trooms)
It gives me ' troom
is not defined' error. 它给我“ troom
”错误。 I don't know how I can pass this object. 我不知道该如何传递该对象。 According to some old post this was working in jade. 根据一些旧帖子,这是在玉器中工作的。 However, I am using the pug version 2.0.0-rc.2
. 但是,我使用的是哈巴狗版本2.0.0-rc.2
。
你可以试试
var trooms = !{JSON.stringify(myrooms)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.