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.
App.svelte
xxxxxxxxxx
5
1
<script>
2
let string = `this string contains some <strong>HTML!!!</strong>`;
3
</script>
4
5
<p>{string}</p>
Console
xxxxxxxxxx
44
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
detach,
5
element,
6
init,
7
insert,
8
noop,
9
safe_not_equal
10
} from "svelte/internal";
11
12
function create_fragment(ctx) {
13
let p;
14
15
return {
16
c() {
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */