Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

通常,字符串以纯文本形式插入,这意味着像 <> 这样的字符没有特殊含义。

¥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) 攻击的风险。

¥[!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.

上一页 下一页
1
2
3
4
5
6
<script>
	let string = `this string contains some <strong>HTML!!!</strong>`;
</script>
 
<p>{string}</p>