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

Viewed 4832

I want to be able to show a code example in my Svelte component, but the example has curly braces, i.e

<script>
//no JS needed
</script>

<p>Here's a sample function</p>
<pre><code>
  function test(e) {
    console.log(e)
  }
</code></pre>

Notice how the function has curly braces? That seems to be confusing the Svelte compiler. Is there a way to escape those other than this?

<script>
//no JS needed
</script>

<p>Here's a sample function</p>
<pre><code>
  function test(e) {'{'}
    console.log(e)
  {'}'}
</code></pre>
1 Answers

I know of 3 ways to escape curly braces in Svelte:

  1. Using {'{'} and {'}'} (What you're already doing)

  2. Using &#123; and &#125;

    or &lbrace; and &rbrace;

    or &lcub; and &rcub;

  3. Using template literals

    You could wrap your whole code inside a template literal.

Examples on svelte.dev's REPL (Partly because I'm having a hard time escaping characters here on SO...)



Discussions on the subject on GitHub:

https://github.com/sveltejs/svelte/issues/2924

https://github.com/sveltejs/svelte/issues/1318



My example on svelte.dev's REPL copy/pasted here just in case something happens to it...

<h3>Escaping every curly brace</h3>
<pre><code>
  function test(e) {'{'}
    console.log(e)
  {'}'}
</code></pre>


<h3>Wrapping the whole code block in a string literal</h3>
<pre><code>
  {`
  function test(e) {
    console.log(e)
  }
  `}
</code></pre>


<h3>Using &#123; and &#125;</h3>
<pre><code>
  function test(e) &#123;
    console.log(e)
  &#125;
</code></pre>

Related