How to pass a Pug JSON object to client side JavaScript

我与影子孤独终老i 提交于 2020-06-27 13:04:11

问题


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.


回答1:


You can try

var trooms = !{JSON.stringify(myrooms)}


来源:https://stackoverflow.com/questions/45644583/how-to-pass-a-pug-json-object-to-client-side-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!