通常,字符串以纯文本形式插入,这意味着像 <
和 >
这样的字符没有特殊含义。
¥Ordinarily, strings are inserted as plain text, meaning that characters like <
and >
have no special meaning.
但有时你需要将 HTML 直接渲染到组件中。例如,你现在正在阅读的单词存在于 markdown 文件中,该文件作为 HTML 块包含在此页面中。
¥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.
在 Svelte 中,你可以使用特殊的 {@html ...}
标签执行此操作:
¥In Svelte, you do this with the special {@html ...}
tag:
App
<p>{@html string}</p>
重要提示:Svelte 在
{@html ...}
中的表达式插入 DOM 之前不会对其进行任何清理。如果内容是你信任的,例如你自己撰写的文章,则不会出现这个问题。但是,如果是一些不受信任的用户内容,例如文章评论,则必须手动对其进行转义,否则用户可能会面临 跨站脚本 (XSS) 攻击的风险。
1
2
3
4
5
6
<script>
let string = `this string contains some <strong>HTML!!!</strong>`;
</script>
<p>{string}</p>