Skip to content

Commit

Permalink
Block Rendering: Add pre-render and post-render filteres
Browse files Browse the repository at this point in the history
Allows for blocks to be structurally and textually filtered during the
rendering process. The pre-filter provides the parsed block object for
transformation while the post-filter provides the rendered output of the
block.

These filters can be used in unison to perform a variety of operations
on blocks. They are applied in a depth-first manner when rendering a
block tree so that deeper-nested blocks are processed before their
parents.

> Caveat: Inner blocks aren't structurally filtered in this patch yet
before their parent.

Actually this needs a lot of work still...
  • Loading branch information
dmsnell committed Nov 12, 2018
1 parent 3eb44f4 commit 7bb8050
Showing 1 changed file with 20 additions and 8 deletions.
28 changes: 20 additions & 8 deletions lib/blocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,25 +142,37 @@ function get_dynamic_blocks_regex() {
function gutenberg_render_block( $block ) {
global $post;

$block_type = WP_Block_Type_Registry::get_instance()->get_registered( $block['blockName'] );
$is_dynamic = $block['blockName'] && null !== $block_type && $block_type->is_dynamic();
$global_post = $post;
$pre_render = apply_filters( 'block_pre_render', $block );
$post = $global_post;

if ( null === $pre_render ) {
return '';
}

$block_type = WP_Block_Type_Registry::get_instance()->get_registered( $pre_render['blockName'] );
$is_dynamic = $pre_render['blockName'] && null !== $block_type && $block_type->is_dynamic();
$inner_content = '';
$index = 0;

foreach ( $block['innerContent'] as $chunk ) {
$inner_content .= is_string( $chunk ) ? $chunk : gutenberg_render_block( $block['innerBlocks'][ $index++ ] );
foreach ( $pre_render['innerContent'] as $chunk ) {
$inner_content .= is_string( $chunk ) ? $chunk : gutenberg_render_block( $pre_render['innerBlocks'][ $index++ ] );
}

if ( $is_dynamic ) {
$attributes = is_array( $block['attrs'] ) ? (array) $block['attrs'] : array();
$attributes = is_array( $pre_render['attrs'] ) ? (array) $pre_render['attrs'] : array();
$global_post = $post;
$output = $block_type->render( $attributes, $inner_content );
$post = $global_post;

return $output;
} else {
$output = $inner_content;
}

return $inner_content;
$global_post = $post;
$post_render = apply_filters( 'block_post_render', $output );
$post = $global_post;

return $post_render;
}

if ( ! function_exists( 'do_blocks' ) ) {
Expand Down

0 comments on commit 7bb8050

Please sign in to comment.