gutenbergdocs/docs/getting-started/fundamentals/markup-representation-block.md
2025-10-22 01:40:18 +08:00

51 lines
3.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 区块的标记表示
区块通过独特的[基于HTML的语法](https://developer.wordpress.org/block-editor/explanations/architecture/key-concepts/#data-and-attributes)存储在数据库或HTML模板中这种语法以HTML注释作为清晰的区块分隔符。这确保了区块标记在技术上是有效的HTML。
以下是定义区块标记的几条准则:
- 核心区块以`wp:`前缀开头,后跟区块名称(例如`wp:image`)。值得注意的是,`core`命名空间被省略。
- 自定义区块以`wp:`前缀开头,后跟区块命名空间和名称(例如`wp:namespace/name`)。
- 注释可以是单行、自闭合或HTML内容的包装器。
- 区块设置和属性以JSON对象形式存储在区块注释内部。
以下是图像区块的简化标记表示:
```html
<!-- wp:image {"sizeSlug":"large"} -->
<figure class="wp-block-image size-large">
<img src="source.jpg" alt="" />
</figure>
<!-- /wp:image -->
```
区块标记在区块编辑器和前端显示区块时都至关重要:
- WordPress在编辑器内分析区块标记以提取其数据并向用户呈现可编辑版本。
- 在前端WordPress再次解析标记以提取数据并渲染最终HTML输出。
<div class="callout callout-tip">
有关区块数据在WordPress中如何解析的深入探讨请参阅<a href="https://developer.wordpress.org/block-editor/explanations/architecture/data-flow/">数据流</a>文章。
</div>
当区块保存时,会执行`save`函数(在[客户端注册区块](https://developer.wordpress.org/block-editor/getting-started/fundamentals/registration-of-a-block/#registration-of-the-block-with-javascript-client-side)时定义)以生成存储在数据库中的标记,并用区块分隔符注释包裹。对于动态渲染的区块(通常将`save`设置为`null`),仅保存带有区块属性的占位符注释。
以下是动态渲染区块(`save` = `null`的标记表示。请注意除了注释外没有HTML标记。
```html
<!-- wp:latest-posts {"postsToShow":4,"displayPostDate":true} /-->
```
当区块具有`save`函数时,区块编辑器会检查`save`函数创建的标记是否与保存到数据库的区块标记相同:
- 差异将触发[验证错误](https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#validation),通常是由于`save`函数输出的更改引起的。
- 开发者可以通过实现[区块弃用](https://developer.wordpress.org/block-editor/reference-guides/block-api/block-deprecation/)来解决潜在的验证问题,以应对更改。
如上例所示动态渲染区块的存储标记非常简洁。通常这只是一个包含区块属性的分隔符注释不受区块编辑器验证的约束。这种方法反映了这些区块的动态特性实际HTML在服务器端生成不存储在数据库中。
## 附加资源
- [数据流与数据格式](https://developer.wordpress.org/block-editor/explanations/architecture/data-flow/)
- [静态与动态区块:有何不同?](https://developer.wordpress.org/news/2023/02/27/static-vs-dynamic-blocks-whats-the-difference/) | 开发者博客
- [区块弃用教程](https://developer.wordpress.org/news/2023/03/10/block-deprecation-a-tutorial/) | 开发者博客
- [模板入门 > 区块标记](https://developer.wordpress.org/themes/templates/introduction-to-templates/#block-markup) | 主题手册