通常,字符串以纯文本形式插入,这意味着像 <
和 >
这样的字符没有特殊含义。
¥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:
<p>{@html string}</p>
重要提示:Svelte 在将
{@html ...}
中的表达式插入 DOM 之前不会对其进行任何清理。如果内容是你信任的内容(例如你自己写的文章),则这不是问题。但是,如果它是一些不受信任的用户内容,例如文章上的评论,那么手动转义它至关重要,否则你将面临用户遭受 跨站点脚本 (XSS) 攻击的风险。¥[!NOTE] Important: Svelte doesn’t perform any sanitization of the expression inside
{@html ...}
before it gets inserted into the DOM. This isn’t an issue if the content is something you trust like an article you wrote yourself. However if it’s some untrusted user content, e.g. a comment on an article, then it’s critical that you manually escape it, otherwise you risk exposing your users to Cross-Site Scripting (XSS) attacks.
<script>
let string = `this string contains some <strong>HTML!!!</strong>`;
</script>
<p>{string}</p>