Inline script does not fire inside render_template in the WP Block Editor

Support MB Blocks Inline script does not fire inside render_template in the WP Block EditorResolved

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #34347
    Nicholas CoxNicholas Cox
    Participant

    Hi,

    I have made a block and all is working ok except I added an inline script inside 'dc-carousel-block-template.php'. I tried running this but found this does not work. It works if I run it inside 'enqueue_script' or 'enqueue_assets'. Is there an issue running inline scripts? or is this just WordPress preventing it?

    Block

    add_filter( 'rwmb_meta_boxes', function( $meta_boxes ) {
        $meta_boxes[] = [
            'title'           => 'Carousel Block',
            'id'              => 'dc-carousel-block',
            'description'     => 'Carousel with product support',
            'type'            => 'block',
            'icon'            => 'screenoptions',
            'category'        => 'dc-blocks',
            'context'         => 'side',
            'render_template' => __DIR__ . '/template/dc-carousel-block-template.php',
    ...
    

    inside 'dc-carousel-block-template.php'

    <script>
    document.addEventListener( 'DOMContentLoaded', function() {
        console.log('testing');
        //test();
    });
    </script>

    Thanks

    #34387
    Long NguyenLong Nguyen
    Moderator

    Hi,

    It looks like WordPress does not support running the inline script when previewing block content (it works on the frontend). You should use the setting enqueue_script to enqueue your script when registering the block. Read more on the documentation
    https://docs.metabox.io/extensions/mb-blocks/#enqueue_script

    #41564
    Key_WebdesignKey_Webdesign
    Participant

    Following up, what about dynamically rendered javascript?
    For example, I want to make a slider block and this slider needs to be initialized. Depending on the Block settings, different javascript should be generated. Now, I can add inline javascript beneath the rendered block HTML but this doesn't fire, as Nicholas already pointed out.
    Any ideas?

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.