5

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.

3
  • You have to out the trooms = "#{myrooms}" before you source the script. Commented Aug 11, 2017 at 22:28
  • Also, need to call JSON.parse('#{myrooms}') to convert JSON to object. Commented Aug 11, 2017 at 22:36
  • 1
    I have tried doing JSON.parse('#{myrooms}') that but it did not work. Commented Aug 12, 2017 at 1:20

1 Answer 1

12

You can try

var trooms = !{JSON.stringify(myrooms)}
Sign up to request clarification or add additional context in comments.

1 Comment

I revert it back to older version of jade and this works. I will work with this for now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.