I tried to write a very simple block plugin for Gutenberg: A simple TOC generator. I can now place a block in a post and the table of contents is being generated as an unordered list. Great! But in the backend (Gutenberg Editor) there is still my ugly block that just say "SimpleTOC" and is not dynamic.
How can I display the output of my php function "render_callback" in the plugin.php https://github.com/mtoensing/simpletoc/blob/0.5/plugin.php in the "edit" function in the JS code? I read my tutorials and looked at core blocks but I just don't get the server side functions.
This is all of my index.js https://github.com/mtoensing/simpletoc/blob/0.5/src/index.js block code:
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;
},
} );
My render_callback function looks like this in plugin.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;
}