WP 6.2中Gutenberg的core/template-part区块前端无法使用已保存属性
解决core/template-part区块前端添加自定义类名的问题
问题根源
core/template-part是特殊的引用型区块,前端渲染时WordPress会直接加载对应模板部件的内容,不会保留该区块自身的DOM结构——这就是你用blocks.getSaveContent.extraProps添加的类名只在编辑器生效、前端不显示的原因。同时它也不会被标记为"渲染区块",因为实际输出的是模板部件的内容而非区块本身。
可行解决方案
要让自定义属性对应的类名在前端生效,最可靠的方式是通过PHP的render_block过滤器拦截模板部件的渲染流程,添加类名:
add_filter( 'render_block', 'add_template_part_custom_class', 10, 2 ); function add_template_part_custom_class( $block_content, $block ) { // 仅处理core/template-part区块 if ( 'core/template-part' !== $block['blockName'] ) { return $block_content; } // 获取已保存的自定义属性 $template_attr = isset( $block['attrs']['templatePartAttributes'] ) ? $block['attrs']['templatePartAttributes'] : ''; if ( empty( $template_attr ) ) { return $block_content; } $custom_class = 'has-' . esc_attr( $template_attr ); // 方案1:给模板部件内容包裹一层带类名的容器 $block_content = sprintf( '<div class="%s">%s</div>', $custom_class, $block_content ); // 方案2(可选):如果模板部件有明确的根元素,直接修改其类名 // $block_content = preg_replace( '/^<([a-z]+)(.*?)>/i', '<$1$2 class="$custom_class">', $block_content, 1 ); return $block_content; }
保留编辑器端的效果
你原来的JS代码可以继续保留,确保编辑器里的区块能显示对应的类名,和前端效果保持一致:
/** * Save */ const saveTemplatePartAttributes = ( extraProps, blockType, attributes ) => { console.log(blockType.name) if ( enableSidebarControlsOnBlocks.includes( blockType.name ) ) { const { templatePartAttributes } = attributes; if ( templatePartAttributes ) { extraProps.className = classnames( extraProps.className, 'has-' + templatePartAttributes ) } } return extraProps; }; wp.hooks.addFilter( 'blocks.getSaveContent.extraProps', 'btt-core/save-template-part-attributes', saveTemplatePartAttributes );
关于getSaveElement钩子的说明
getSaveElement钩子仅作用于编辑器内的区块渲染,无法影响前端PHP生成的输出,所以不能用它来实现前端类名的添加。如果需要在编辑器里调整区块的显示,它可以用来修改编辑器内的元素结构,但前端渲染必须依赖PHP过滤器。
内容的提问来源于stack exchange,提问作者bjoernbear
相关产品推荐
相关产品推荐

