glocore
glocore

Reputation: 2154

How to add unescaped stringified JSON in EJS?

I'm trying to send a postMessage using JavaScript in an EJS template, and I need to send a simple stringified JSON object that looks like this:

{ "id": "1234567890" }

When I try to pass this object in an EJS template, the double-quotes (") get escaped into ". Here's my template:

<script>
    if (window.opener) {
        window.opener.postMessage('<%= JSON.stringify(user) %>', "http://localhost:3000")
        window.close()
    }
</script>

The stringified object gets turned into this:

&#34;{&#34;id&#34;:&#34;1234567890&#34;}&#34;

What can I do to prevent the special characters from being escaped by EJS?

Upvotes: 0

Views: 340

Answers (1)

glocore
glocore

Reputation: 2154

Turns out I need to replace <%= with <%- to use unescaped characters.

So my code would have to be:

<script>
    if (window.opener) {
        window.opener.postMessage('<%- JSON.stringify(user) %>', "http://localhost:3000")
        window.close()
    }
</script>

Source: https://github.com/tj/ejs/tree/1.0.0#features

Upvotes: 0

Related Questions