Rendering javascript in render_callback php Code

Question

I’ve got a block-based plugin that displays a leafletjs map. The map displays perfectly in a WP Post. However, in the block editor, the map fails to display. The heading2, ‘Leaflet.js Map’ shows, with a blank space below where the map should be.

It looks like the javascript to display the leaflet map isn’t being executed in the editor.

Render_callback function to display the map

function showMap($atts) {

    $maphtml = "<h2>Leaflet.js Map</h2>";

    $maphtml = $maphtml . "<div id="mapid" style="width: 100%; height: 400px;"></div>";

    $maphtml = $maphtml . "<script>
    var map = new L.map('mapid', {zoomControl:false,
    layers: [
        new L.TileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            'attribution': 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
        })
    ],
    center: [51.505, -0.09],
    zoom: 13
    });

    </script>";
    return $maphtml;
}

and is registered here:

    register_block_type(
        'cgb/block-my-block', array(
            // Enqueue blocks.style.build.css on both frontend & backend.
            'style'         => 'my_block-cgb-style-css',
            // Enqueue blocks.build.js in the editor only.
            'editor_script' => 'my_block-cgb-block-js',
            // Enqueue blocks.editor.build.css in the editor only.
            'editor_style'  => 'my_block-cgb-block-editor-css',

            'render_callback' => 'showMap',
        )
    );

Loading css & js for Leafletjs

function leafletjs_load(){
    // Custom css for table containing map and data
    $cssurl = plugins_url('/styles/showfitfile.css', __FILE__);
    wp_enqueue_style('showfitfile_css', $cssurl);

    //CSS and JS for Leaflet
    $leafletcss = plugins_url('/styles/leaflet.css', __FILE__);
    $leafletjs = plugins_url('/styles/leaflet.js', __FILE__);
    wp_enqueue_style('leafletjs_css', $leafletcss);
    wp_enqueue_script('leafletjs', $leafletjs);
}

add_action('enqueue_block_assets', 'leafletjs_load');

The editor javascript code

    edit: ( props ) => {
        const { attributes, setAttributes } = props;
        // Creates a <p class="wp-block-cgb-block-my-block"></p>.
        return (
            <ServerSideRender
                block = "cgb/block-my-block"
            />
        );
    },

Trying to troubleshoot this, I get the impression that it’s not possible to render javascript within the render_callback php code, and I’ll need to rewrite the block editor entirely in javascript. Is this correct, or have I messed up somewhere else?

0
Stuart Tevendale 2 weeks 2021-07-13T14:24:04-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse