1

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. 😬

2
  • <pre>{JSON.stringify({ "num": 2, "obj": { "foo": "bar" }}, null, 2)}</pre>, or assign it to a variable in the <script> section as a template literal. REPL
    – pilchard
    Sep 20, 2021 at 21:01
  • 1
    Argh! I find it so difficult to remember to include null, 2. Thanks for the reminder, @pilchard!
    – Navelgazer
    Sep 20, 2021 at 21:14

1 Answer 1

3

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?

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.