Themes: Inject `theme` attribute during serialization.

Rather than using `_inject_theme_attribute_in_block_template_content` to inject the `theme` attribute into all Template Part blocks found in a given file-based Block Template, introduce a new function called `_inject_theme_attribute_in_template_part_block`, and use that as second argument to `serialize_blocks()` (introduced in [56557]) in order to inject said attribute during tree traversal for serialization.

This allows for a more modular approach that will eventually be extended to implement automatic insertion of hooked blocks.

Note that we're guarding `_build_block_template_result_from_file()` (i.e. the callsite of `_inject_theme_attribute_in_template_part_block` and previously of `_inject_theme_attribute_in_block_template_content`) against regressions through additional unit test coverage added in [56562].

Props @gziolo.
Fixes #59338. See #59313.
Built from https://develop.svn.wordpress.org/trunk@56578


git-svn-id: http://core.svn.wordpress.org/trunk@56090 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Bernhard Reiter 2023-09-14 08:52:19 +00:00
parent da2581b4c1
commit 172397e6e5
2 changed files with 24 additions and 2 deletions

View File

@ -513,6 +513,26 @@ function _inject_theme_attribute_in_block_template_content( $template_content )
return $template_content;
}
/**
* Injects the active theme's stylesheet as a `theme` attribute
* into a given template part block.
*
* @since 6.4.0
* @access private
*
* @param array $block a parsed block.
* @return array Updated block.
*/
function _inject_theme_attribute_in_template_part_block( $block ) {
if (
'core/template-part' === $block['blockName'] &&
! isset( $block['attrs']['theme'] )
) {
$block['attrs']['theme'] = get_stylesheet();
}
return $block;
}
/**
* Parses a block template and removes the theme attribute from each template part.
*
@ -565,7 +585,6 @@ function _build_block_template_result_from_file( $template_file, $template_type
$template = new WP_Block_Template();
$template->id = $theme . '//' . $template_file['slug'];
$template->theme = $theme;
$template->content = _inject_theme_attribute_in_block_template_content( $template_content );
$template->slug = $template_file['slug'];
$template->source = 'theme';
$template->type = $template_type;
@ -589,6 +608,9 @@ function _build_block_template_result_from_file( $template_file, $template_type
$template->area = $template_file['area'];
}
$blocks = parse_blocks( $template_content );
$template->content = serialize_blocks( $blocks, '_inject_theme_attribute_in_template_part_block' );
return $template;
}

View File

@ -16,7 +16,7 @@
*
* @global string $wp_version
*/
$wp_version = '6.4-alpha-56577';
$wp_version = '6.4-alpha-56578';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.