21

I have tried rendering the html by storing the html in a variable but it is not working , I also tried the triple curly braces

<script>
    let name = 'world';
    let val = ""
    let ans2 = ""
    let ans3;
    import showdown from 'showdown';
    import validity from 'validity-checker';
    function dataSubmit(e){
        e.preventDefault();
    //ans = validity.isEmoji("ggg");
    ans2 = new showdown.Converter();
    ans3 = ans2.makeHtml(val)
    }
</script>

<div>
    <textarea bind:value={val} on:change={dataSubmit}></textarea>
    <div>
    {{{ans3}}}  
    </div>
    
</div>

Return type of the ans3 variable is like "<h1>Hello</h1>"

Hypermystic
  • 880
  • 2
  • 11
  • 22

3 Answers3

43

You can use {@html expression}

Svelte does not sanitize expressions before injecting HTML. If the data comes from an untrusted source, you must sanitize it, or you are exposing your users to an XSS vulnerability.

CD..
  • 72,281
  • 25
  • 154
  • 163
2

Ordinarily, strings are inserted as plain text, meaning that characters like < and > have no special meaning.

But sometimes you need to render HTML directly into a component. For example, the words you're reading right now exist in a markdown file that gets included on this page as a blob of HTML.

In Svelte, you do this with the special {@html ...} tag:

<p>{@html string}</p>

Svelte doesn't perform any sanitization of the expression inside {@html ...} before it gets inserted into the DOM. In other words, if you use this feature it's critical that you manually escape HTML that comes from sources you don't trust, otherwise you risk exposing your users to XSS attacks.

From https://svelte.dev/tutorial/html-tags

Paolo
  • 20,112
  • 21
  • 72
  • 113
Sateesh
  • 131
  • 8
1

Like Sateesh and CD.. answered, {@html expression : string} renders your html string as html. But it won't work if you pass in a HTML object.

If you want svelte to display a HTML object you instantiated in JavaScript, just need to specify a target and either set or append the element as its child like this:

let myComponent = document.createElement('div');

document.getElementById('parent').appendChild(myComponent);

Reactivity is still preserved.

Psionman
  • 3,084
  • 1
  • 32
  • 65
MohaElder
  • 41
  • 4