Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

svelte

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>
like image 557
Steven Bell Avatar asked Apr 07 '20 20:04

Steven Bell


People also ask

How do you escape a curly bracket?

The current workaround is to use backslash as an escape character: however, on some instances that uses a lot of links of this kind, this workaround is very troublesome.

How do you escape curly brackets in JSON?

Curly braces do not have to be escaped in JSON. Show activity on this post. No, curly braces do not have to be escaped in JSON strings. JSON is defined in RFC 7159.

Do I need to escape curly braces in regex?

To match literal curly braces, you have to escape them with \ . However, Apex Code uses \ as an escape, too, so you have to "escape the escape". You'll need to do this almost every time you want to use any sort of special characters in your regexp literally, which will happen more frequently than not.


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>
like image 135
Félix Paradis Avatar answered Sep 25 '22 17:09

Félix Paradis