Handle translations in lazy loaded files by injecting them into the page (https://github.com/woocommerce/woocommerce-blocks/pull/4897)

* Formalise chunk names

* register_chunk_translations()

* Rename handle

* Include fileSuffix

* Remove .chunk prefix- it broke the vendors chunk
This commit is contained in:
Mike Jolley 2021-10-11 16:32:29 +01:00 committed by GitHub
parent 9fbfb5a594
commit caaa4f5ac4
2 changed files with 45 additions and 0 deletions

View File

@ -152,6 +152,26 @@ abstract class AbstractBlock {
}
}
/**
* Injects Chunk Translations into the page so translations work for lazy loaded components.
*
* The chunk names are defined when creating lazy loaded components using webpackChunkName.
*
* @param string[] $chunks Array of chunk names.
*/
protected function register_chunk_translations( $chunks ) {
foreach ( $chunks as $chunk ) {
$handle = 'wc-blocks-' . $chunk . '-chunk';
$this->asset_api->register_script( $handle, $this->asset_api->get_block_asset_build_path( $chunk ), [], true );
wp_add_inline_script(
$this->get_block_type_script( 'handle' ),
wp_scripts()->print_translations( $handle, false ),
'before'
);
wp_deregister_script( $handle );
}
}
/**
* Registers the block type with WordPress.
*/

View File

@ -28,4 +28,29 @@ class AllProducts extends AbstractBlock {
$this->asset_data_registry->add( 'max_rows', wc_get_theme_support( 'product_blocks::max_rows', 6 ), true );
$this->asset_data_registry->add( 'default_rows', wc_get_theme_support( 'product_blocks::default_rows', 3 ), true );
}
/**
* Register script and style assets for the block type before it is registered.
*
* This registers the scripts; it does not enqueue them.
*/
protected function register_block_type_assets() {
parent::register_block_type_assets();
$this->register_chunk_translations(
[
'atomic-block-components/price',
'atomic-block-components/image',
'atomic-block-components/title',
'atomic-block-components/rating',
'atomic-block-components/button',
'atomic-block-components/summary',
'atomic-block-components/sale-badge',
'atomic-block-components/sku',
'atomic-block-components/category-list',
'atomic-block-components/tag-list',
'atomic-block-components/stock-indicator',
'atomic-block-components/add-to-cart',
]
);
}
}