0
0
Svelteframework~5 mins

HTML rendering with {@html} in Svelte

Choose your learning style9 modes available
Introduction

Sometimes you want to show HTML code stored in a variable as real HTML on the page, not just plain text.

Displaying user-generated content that includes HTML tags.
Showing formatted text from a database or API response.
Rendering small snippets of trusted HTML inside your component.
Syntax
Svelte
{@html variableContainingHtml}

This tells Svelte to treat the variable's content as HTML, not plain text.

Be careful: only use with trusted content to avoid security risks.

Examples
This renders the word Hello! in bold inside the paragraph.
Svelte
<script>
  let htmlContent = '<strong>Hello!</strong>';
</script>

<p>{@html htmlContent}</p>
This shows a bulleted list with two items inside the div.
Svelte
<script>
  let listHtml = '<ul><li>Apple</li><li>Banana</li></ul>';
</script>

<div>{@html listHtml}</div>
This example shows why you must only use trusted HTML, because it can run harmful scripts.
Svelte
<script>
  let unsafeHtml = '<img src=x onerror="alert(1)" />';
</script>

<p>{@html unsafeHtml}</p>
Sample Program

This component shows the difference between showing HTML as plain text and rendering it as real HTML.

Svelte
<script>
  let message = '<em>Welcome to Svelte!</em>';
</script>

<main>
  <h1>HTML Rendering Example</h1>
  <p>Normal text: {message}</p>
  <p>Rendered HTML: {@html message}</p>
</main>
OutputSuccess
Important Notes

Never use {@html} with untrusted content to avoid security problems like cross-site scripting (XSS).

If you want to show HTML code as text, just use curly braces without {@html}.

Summary

{@html} lets you render HTML stored in variables as real HTML inside your Svelte components.

Use it only with safe, trusted HTML to keep your app secure.

It helps when you want to display formatted content dynamically.