我也遇到了这个问题,我所做的是在PHP中定义属性并使用wp_localize_script
传递数组。
然后您可以将变量传入render_callback
使用use ($var)
例如:
$js = get_stylesheet_directory_uri() . \'/assets/js\';
$css= get_stylesheet_directory_uri() . \'/assets/css\';
$default_attributes = [
\'alignment\' => [ \'type\' => \'string\', \'default\' => \'left\' ],
\'iconPosition\' => [ \'type\' => \'string\', \'default\' => \'left\' ],
\'textColor\' => [ \'type\' => \'string\', \'default\' => \'var(--text)\' ],
\'bgColor\' => [ \'type\' => \'string\', \'default\' => \'var(--textInvert)\' ],
];
wp_register_script( \'my-block\', $dist . \'/my-block.js\', [ \'wp-blocks\', \'wp-dom\' ] , null, true );
wp_register_style( \'my-block\', $dist . \'/my-block.css\', [ \'wp-edit-blocks\' ] );
wp_localize_script( \'my-block\', \'myBlockLocalize\', [ \'attributes\' => $default_attributes ] );
register_block_type( \'my/block\', [
\'editor_style\' => \'my-block\',
\'editor_script\' => \'my-block\',
\'render_callback\' => function( $atts, $inner_blocks = null ) use ( $default_attributes ) {
$default_values = array_map( function( $a ) {
return $a[\'default\'] ?? \'\';
}, $default_attributes );
$atts = wp_parse_args( $atts, $default_values );
ob_start();
// output the HTML here, I believe you can use get_template_parts()
return ob_get_clean();
}
] );
在您的JS中:
...
registerBlockType( \'my/block\', {
title: \'My Block\',
icon: \'id\',
category: \'layout\',
example: {},
attributes: myBlockLocalize.attributes,
// ...
} );
...