我试图为Gutenberg编写一个非常简单的块插件:一个简单的TOC生成器。我现在可以在帖子中放置一个块,目录将作为无序列表生成。太棒了但在后端(Gutenberg编辑器),仍然有我的丑陋块,只说“SimpleTOC”,不是动态的。
如何在插件中显示php函数“render\\u callback”的输出。phphttps://github.com/mtoensing/simpletoc/blob/0.5/plugin.php 在JS代码的“编辑”功能中?我阅读了教程并查看了核心模块,但我不了解服务器端的功能。
这是我所有的索引。js公司https://github.com/mtoensing/simpletoc/blob/0.5/src/index.js 块代码:
const { __, setLocaleData } = wp.i18n;
const { registerBlockType } = wp.blocks;
registerBlockType( \'simpletoc/toc\', {
title: __( \'Table of Contents\', \'simpletoc\' ),
icon: \'list-view\',
category: \'layout\',
edit( { className } ) {
return <p className={ className }>
<ul>
<li>SimpleTOC</li>
<li>SimpleTOC</li>
<li>SimpleTOC</li>
</ul>
</p>;
},
save: props => {
return null;
},
} );
我的render\\u回调函数在插件中类似于此。php
https://github.com/mtoensing/simpletoc/blob/0.5/plugin.php:
function render_callback( $attributes, $content ) {
$blocks = parse_blocks( get_the_content( get_the_ID()));
if ( empty( $blocks ) ) {
return \'No contents.\';
}
//add only if block is used in this post.
add_filter( \'render_block\', __NAMESPACE__ . \'\\\\filter_block\', 10, 2 );
$headings = array_values( array_filter( $blocks, function( $block ){
return $block[\'blockName\'] === \'core/heading\';
}) );
if ( empty( $headings ) ) {
return \'No headings.\';
}
$heading_contents = array_column( $headings, \'innerHTML\');
$output .= \'<ul class="toc">\';
foreach ( $heading_contents as $heading_content ) {
preg_match( \'|<h[^>]+>(.*)</h[^>]+>|iU\', $heading_content , $matches );
$link = sanitize_title_with_dashes( $matches[1]);
$output .= \'<li><a href="#\' . $link . \'">\' . $matches[1] . \'</a></li>\';
}
$output .= \'</ul>\';
return $output;
}
最合适的回答,由SO网友:Marc 整理而成
我不得不在php(init)包中添加serversiderender作为组件。js和js代码。
php中的初始化
wp_register_script(
\'simpletoc\',
plugins_url(\'build/index.js\', __FILE__),
[ \'wp-blocks\', \'wp-i18n\', \'wp-element\', \'wp-server-side-render\' ],
filemtime(plugin_dir_path(__FILE__) . \'build/index.js\')
);
区块js:
const { __, setLocaleData } = wp.i18n;
const { registerBlockType } = wp.blocks;
import ServerSideRender from \'@wordpress/server-side-render\';
registerBlockType( \'simpletoc/toc\', {
title: __( \'SimpleTOC\', \'simpletoc\' ),
icon: \'list-view\',
category: \'layout\',
edit: function( props ) {
return (
<p className={ props.className }>
<ServerSideRender
block="simpletoc/toc"
attributes={ props.attributes }
/>
</p>
);
},
save: props => {
return null;
},
} );
并将其安装到环境中:
npm install @wordpress/server-side-render --save
我忘记了第一步,然后就成功了。在此处填写工作脚本:
https://github.com/mtoensing/simpletoc/tree/0.6