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>
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.
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.
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.
I know of 3 ways to escape curly braces in Svelte:
Using {'{'}
and {'}'}
(What you're already doing)
Using {
and }
or {
and }
or {
and }
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 { and }</h3>
<pre><code>
function test(e) {
console.log(e)
}
</code></pre>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With