Terence Chow Terence Chow - 4 months ago 33
Jade Question

How to add stringified script tag in express + jade/pug

I have express using pug as a view. My index.pug has the following:

window.__DATA__ = !{payload}

where payload is a json object. It has been stringified in the render function of express:

res.render('index', {
payload : JSON.stringify({
"anExample": "<script></script>"

When my Json object has
it terminates my
window.__DATA =
function early due to the ending script tag. How can I prevent this from blowing up my page? Is this a limitation of Pug or Express or the browser?


After asking around the solution is to use a stringify library instead of using the provided JSON.stringify function.

Specifically I used the npm module js-stringify which changes the < characters into unicode in addition to stringifying the json. Hence that is then able to be inserted into a a templating engine like Pug. Pug can then unescape it with !{my_stringified_json}. Since it unescapes unicode back to its original, the json ends up being 'anExample: '<script></script'> instead of it's unicode equivalent.