块编辑器开发文档

解析器过滤器

💡 云策文档标注

概述

本文档介绍了 WordPress 编辑器中块数据的序列化与解析过程,以及如何通过过滤器替换服务器端解析器。块在编辑器中以数据结构形式存储,保存时序列化为 HTML 结构,加载时通过解析器反向转换。

关键要点

  • 块数据在编辑器中存储为数据结构,保存时序列化为 HTML 并存入 post_content。
  • 加载时使用块解析器将 HTML 反序列化为数据结构,基于 @wordpress/block-serialization-spec-parser 包的 PEG 规范。
  • 服务器端解析器可通过 block_parser_class 过滤器替换,客户端解析器目前不可替换。
  • 插件可使用解析器处理结构化帖子数据,而非纯 HTML 字符串。

代码示例

class EmptyParser {
  public function parse( $post_content ) {
    // return an empty document
    return array();
  }
}

function wpdocs_select_empty_parser( $prev_parser_class ) {
    return 'EmptyParser';
}

add_filter( 'block_parser_class', 'wpdocs_select_empty_parser', 10, 1 );

注意事项

目前无法替换客户端解析器。


📄 原文内容

When the editor is interacting with blocks, these are stored in memory as data structures comprising a few basic properties and attributes. Upon saving a working post we serialize these data structures into a specific HTML structure and save the resultant string into the post_content property of the post in the WordPress database. When we load that post back into the editor we have to make the reverse transformation to build those data structures from the serialized format in HTML.

The process of loading the serialized HTML into the editor is performed by the block parser. The formal specification for this transformation is encoded in the parsing expression grammar (PEG) inside the @wordpress/block-serialization-spec-parser package. The editor provides a default parser implementation of this grammar but there may be various reasons for replacing that implementation with a custom implementation. We can inject our own custom parser implementation through the appropriate filter.

Server-side parser

Plugins have access to the parser if they want to process posts in their structured form instead of a plain HTML-as-string representation.

Client-side parser

The editor uses the client-side parser while interactively working in a post. The plain HTML-as-string representation is sent to the browser by the backend and then the editor performs the first parse to initialize itself.

Filters

To replace the server-side parser, use the block_parser_class filter. The filter transforms the string class name of a parser class. This class is expected to expose a parse method.

Example:

class EmptyParser {
  public function parse( $post_content ) {
    // return an empty document
    return array();
  }
}

function wpdocs_select_empty_parser( $prev_parser_class ) {
    return 'EmptyParser';
}

add_filter( 'block_parser_class', 'wpdocs_select_empty_parser', 10, 1 );

Note: At the present time it’s not possible to replace the client-side parser.