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

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