The block name is not passed as a parameter to the render_callback callback function. This means it's not possible to use a generic callback which performs routing to render dynamic blocks (for example, a generic handler which routes block rendering to theme template parts).
The block name is passed as a parameter to the render_callback callback function.
Just the block attributes and content are passed.
There are a number of "convert your shortcode to a block" tutorials that use the shortcode callback as the render_callback function, which is conveniently possible because the two callbacks share function signatures.
shortcode_callback( $attributes, $content, $shortcode_tag );render_callback( $attributes, $content );So there's three easy solutions:
You can pass block name via attributes using filter in php's render_block function.
function pass_block_name_to_render( $block, $source_block ) {
$block['attrs']['_name'] = $block['blockName'];
return $block;
}
add_action( 'render_block_data', 'pass_block_name_to_render', 10, 2 );
You can then access it in the render callback like this: $attributes['_name']
A possible solution to this is being explored at https://github.com/WordPress/gutenberg/pull/21467#issuecomment-613635022 , where render_callback would be provided an instance of a block class containing all properties relevant to that block (including name), while still retaining backwards-compatibility by having the class implement ArrayAccess so that array access is treated as it behaves today with retrieving attributes of the block.
These would both work, and effectively behave the same:
register_block_type( 'my-plugin/favorite-color', [
'render_callback' => function( $block_attributes ) {
return 'Favorite color is: ' . esc_html( $block_attributes['color'] );
}
] );
register_block_type( 'my-plugin/favorite-color', [
'render_callback' => function( $block ) {
return 'Favorite color is: ' . esc_html( $block->attributes['color'] );
}
] );
It's still an early iteration, but feedback is welcome.
This is now possible as of the changes merged in #21467.
See documentation: https://github.com/WordPress/gutenberg/blob/master/docs/designers-developers/developers/tutorials/block-tutorial/creating-dynamic-blocks.md
Example:
register_block_type( 'my-plugin/favorite-color', [
'render_callback' => function( $block ) {
return 'Block name: ' . esc_html( $block->name );
}
] );
Most helpful comment
You can pass block name via attributes using filter in php's render_block function.
You can then access it in the render callback like this:
$attributes['_name']