Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Block API: Block Context: Filter content, prepare attributes at render, pass block to render #21925

Merged
merged 18 commits into from
May 5, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion lib/compat.php
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,16 @@ function gutenberg_render_block_with_assigned_block_context( $pre_render, $parse

/** This filter is documented in src/wp-includes/blocks.php */
$parsed_block = apply_filters( 'render_block_data', $parsed_block, $source_block );
$context = array( 'postId' => $post->ID );
$context = array(
'postId' => $post->ID,
/*
* The `postType` context is largely unnecessary server-side, since the
* ID is usually sufficient on its own. That being said, since a block
* manifests is expected to be shared between the server and the client,
aduth marked this conversation as resolved.
Show resolved Hide resolved
* it should be included to consistently fulfill the expectation.
*/
'postType' => $post->post_type,
);
$block = new WP_Block( $parsed_block, $context );

return $block->render();
Expand Down
34 changes: 34 additions & 0 deletions phpunit/class-block-context-test.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,38 @@ function test_provides_block_context() {
);
}

/**
* Tests that a block can receive default-provided context through
* render_block.
*/
function test_provides_default_context() {
global $post;

$provided_context = array();

$this->register_block_type(
'gutenberg/test-context-consumer',
array(
'context' => array( 'postId', 'postType' ),
'render_callback' => function( $attributes, $content, $block ) use ( &$provided_context ) {
$provided_context[] = $block->context;

return '';
},
)
);

$parsed_blocks = parse_blocks( '<!-- wp:gutenberg/test-context-consumer /-->' );

render_block( $parsed_blocks[0] );

$this->assertEquals(
array(
'postId' => $post->ID,
'postType' => $post->post_type,
),
$provided_context[0]
);
}

}