How to render html in svelte
Asked Answered
J

3

30

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>"

Jasminejason answered 20/8, 2019 at 18:58 Comment(0)
R
59

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.

Retail answered 20/8, 2019 at 19:1 Comment(3)
This doesn't work for me. I get entity encoded htmlLorola
@Lorola see a working exampleRetail
Is this only static? Updating expression seems fruitless.Leap
Y
7

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

Yuan answered 11/11, 2021 at 11:44 Comment(0)
D
2

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.

Dariusdarjeeling answered 5/4, 2023 at 4:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.