34

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

3 Answers 3

66

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This doesn't work for me. I get entity encoded html
@chovy see a working example
Is this only static? Updating expression seems fruitless.
9

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.