如何在Gutenberg动态块渲染回调中实现include_once效果?
Gutenberg动态块实现模板片段仅加载一次的问题与解决方案
问题描述
我开发的自定义插件包含一个Gutenberg动态块,使用PHP函数作为其render_callback。我希望该渲染函数能实现类似PHP include_once()的效果来引入模板片段。
我可以使用get_template_part,但需要实现:不管页面/文章中该块被使用多少次,指定的模板片段仅执行一次(和include_once特性一致)。
现有代码
block.php中的块注册代码:
register_block_type( __DIR__ . '/build/chart', [ 'render_callback' => 'chart_render', 'attributes' => [ 'theFile' => [ 'type' => 'string', 'default' => '' ], 'theVars' => [ 'type' => 'string', 'default' => '' ] ] ] );
渲染函数代码:
function chart_render($attr, $content) { ob_start(); get_template_part($path_to_template_part, null); $ret = ob_get_contents(); ob_end_clean(); return $ret; }
我需要引入一个驱动图表的独立PHP文件,但无论页面中该块被插入多少次,这个文件仅加载一次。直接在渲染函数中加include_once()会导致文件内容输出在HTML标签最上方,而不是块所在的内容位置。
尝试过的无效方法
我试过用has_block()配合init钩子,这种方法对脚本入队有效,但用include_once()时还是会出现内容提前输出的问题:
function my_dependencies () { if(has_blocks('chart')) { include_once ('my_path/myfile.php' ); } } add_action( 'init', 'my_dependencies' );
- 把这个函数放在
block.php中时,has_blocks始终返回false,推测是因为块注册时文章内容还未加载。 - 把函数放到渲染函数调用的模板片段中,内容依然会输出在HTML标签前。
补充说明:我做这个的原因是,我的专用主题允许编辑选择文章中加载的特定图表及参数数组,而这些图表依赖的PHP文件只需在文章中出现一次,不需要每个块都加载一次。
有效解决方案
@S.Walsh指出可以在输出缓冲(Output Buffer)内使用include_once(),问题迎刃而解。以下是可用代码:
function chart_render($attr, $content) { ob_start(); include_once(my_path/myfile.php); // 无论文章中有多少个该块,仅加载一次 get_template_part($path_to_template_part, null); // 每个块都会加载此模板片段 $ret = ob_get_contents(); ob_end_clean(); return $ret; }
内容的提问来源于stack exchange,提问作者red5
相关产品推荐
相关产品推荐

