admin管理员组文章数量:1279242
I am trying to pass a JSON object from pug to client side JavaScript. Here's how the code is structured. I render a JSON object and pass it to Pug from my Node-Express backend. Code below:
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. Now I want to pass it to a client side script. I am doing something like this in my index.pug
file.
index.pug
:
script(src='/js/play.js').
trooms = "#{myrooms}"
play.js
:
console.log(trooms)
It gives me 'troom
is not defined' error. 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
.
I am trying to pass a JSON object from pug to client side JavaScript. Here's how the code is structured. I render a JSON object and pass it to Pug from my Node-Express backend. Code below:
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. Now I want to pass it to a client side script. I am doing something like this in my index.pug
file.
index.pug
:
script(src='/js/play.js').
trooms = "#{myrooms}"
play.js
:
console.log(trooms)
It gives me 'troom
is not defined' error. 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
.
-
You have to out the
trooms = "#{myrooms}"
before you source the script. – lxe Commented Aug 11, 2017 at 22:28 -
Also, need to call
JSON.parse('#{myrooms}')
to convert JSON to object. – alexmac Commented Aug 11, 2017 at 22:36 -
1
I have tried doing
JSON.parse('#{myrooms}')
that but it did not work. – Shadid Commented Aug 12, 2017 at 1:20
1 Answer
Reset to default 12You can try
var trooms = !{JSON.stringify(myrooms)}
本文标签: nodejsHow to pass a Pug JSON object to client side JavaScriptStack Overflow
版权声明:本文标题:node.js - How to pass a Pug JSON object to client side JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741239871a2363763.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论