Search code examples
jsonsveltepre

How do I prevent Svelte from flattening JSON inside a <pre> tag?


As demonstrated in this REPL, inserting JSON between <pre> tags results in an error. My question was going to be, "What's up with this error?", but then I realized that the single brackets are seen as executable code by Svelte (duh), so I can't just treat it like HTML.

THAT SAID…

How can I take this content, which works fine as raw HTML…

<pre>
{
  "num": 2,
    "obj": { "foo": "bar" }
}
</pre>

and keep the carriage returns so that it renders with white space, like so ↓ ?

{
  "num": 2,
    "obj": { "foo": "bar" }
}

Note: My first attempt gets past the error, but wipes out all white space before the pre tag can protect it:

{"num":2,"obj":{"foo":"bar"}}

Hopefully I'm missing something bone-headedly simple here. 😬


Solution

  • These are the three options that come to mind.

    A straight template literal inside a code block.

    <pre>{`{
      num: 2,
      obj: { "foo": "bar" }
    }`}
    </pre>
    

    A template literal declared in the script section

    <script>
        let json = `{
      num: 2,
      obj: { "foo": "bar" }
    }`
    </script>
    
    <pre>{json}</pre>
    

    JSON.stringify()

    <pre>{JSON.stringify({ "num": 2, "obj": { "foo": "bar" }}, null, 2)}</pre>
    

    REPL

    Also see: Using Svelte, how can I escape curly braces in the HTML?