Linguine Code

How to render a function with HTML in Svelte

How do you call a custom function with HTML code, and render it in Svelte?

For example:

  const renderGreet = mssg => `<h1>${mssg}</h1>`;

{renderGreet("Hello World!")}

Note that in my renderGreet() function I’m wrapping my html code with backticks (``).

If you don’t do that your Svelte application will break. This isn’t JSX.

Another thing to note is that strings in Svelte are inserted as just plain text. Special characters like brackets (<>) have no special meaning.

The code example above would render as such

Svelte function with HTML plain text output

So how do we solve for this?

Solution: Use @html tags expressions

{@html expression} expressions allows Svelte to make those special characters have meaning.

  const renderGreet = mssg => `<h1>${mssg}</h1>`;

{@html renderGreet("Hello World!")}
Use html tag expression to render function with HTML

When you’re using this this expression type, you have to make sure

It’s valid HTML

{@html '
'}Hello World{@html '

Doing something like this may render “Hello World,” but it will not generate the HTML as you would expect.

HTML tree structure

Sanitize before injecting

If you’re making an API to an untrusted source that returns HTML content, make sure to sanitize.

That way you don’t expose your users to XSS (cross-site scripting) vulnerabilities.


I would only use this approach when I have no control of the HTML.

This is usually the case when you’re fetch data dynamically, and that API is returning HTML back.

But if you do have control of the HTML markup, I would extract that content into it’s own Svelte component file, and use <svelte:component /> directive.