CybeX
CybeX

Reputation: 2396

store nodejs object inside pug script tag

I have a few objects I need to render/store in my pug file for later use in client side JS scripts.

To store objects inside a script tag, I would use the method described here and here:

NodeJS variable

const object = {
    "someKey": {
        "message":"this works"
    }
}
res.render("index", {object});

pug (somewhere in file - note the . after the script tag)

note also I am using double quotes - you can use single quotes but I mention this for later

script.
    var object = JSON.parse("!{JSON.stringify(object)}")

then somewhere in your javascript scripts

alert(object.someKey.message)

Read up more about Pug Interpolation here.

Problem:

For all my uses, the above example works fine. The problem comes in when I have an object with a single quote inside:

const object = {
    "someKey": {
        "message":"this doesn't work"
    }
}

Javascript doesn't like the fact that there is a single quote, as it sees the single quote as the start/end of a object key/value:

getting this from Chrome console enter image description here

Cause: enter image description here

Removing this single quote solves the problem. When hitting this point, the JSON.parse() function throws the exception and stops loading any and all JS, thus, no further functions work. A work around is to put this at the very end of the page, but that doesn't solve the problem.

Question:

How can I pass in an object from NodeJS to pug (as shown above) with single-quotes?


Update

MCVE of issue using standard NodeJS expresss boiler plate

https://github.com/cybex-dev/pug-single-quote-isse

Setup Instructions:

git clone https://github.com/cybex-dev/pug-single-quote-isse
npm install 
npm start

You should see expect to see some console output, I simply see:

enter image description here

and "error line"

enter image description here

Upvotes: 2

Views: 525

Answers (2)

Bret Weinraub
Bret Weinraub

Reputation: 2283

Sorry the other solution isn't clear.

Simply:

script.
  var object = !{JSON.stringify(object)};

//- don't forget a blank line to close your script block

Upvotes: 0

tom
tom

Reputation: 10539

I can't reproduce your working example with:

script.
    var object = JSON.parse("!{JSON.stringify(object)}")

But what works for me is this:

script.
    var object = !{JSON.stringify(object)};
    console.log(object.someKey.message);

Without double quotes: var object = !{JSON.stringify(object)}

Upvotes: 2

Related Questions