Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render html in svelte

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

like image 357
Hypermystic Avatar asked Aug 20 '19 18:08

Hypermystic


People also ask

How do you render a tag in HTML?

The Render Functionrender() function takes two arguments, HTML code and an HTML element. The purpose of the function is to display the specified HTML code inside the specified HTML element.

What is $: In svelte?

$: marks a statement as reactive Reactive statements run after other script code and before the component markup is rendered, whenever the values that they depend on have changed.


2 Answers

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.

like image 113
CD.. Avatar answered Oct 18 '22 20:10

CD..


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:

{@html string}

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

like image 1
Sateesh Avatar answered Oct 18 '22 20:10

Sateesh