Share unique ID with render_template and JS asset
- This topic has 2 replies, 2 voices, and was last updated 3 years, 1 month ago by
Nicholas Cox.
-
AuthorPosts
-
March 14, 2022 at 5:21 PM #34511
Nicholas Cox
ParticipantHi
I have been testing and found it is difficult to pass a unique ID for my carousel library. The library targets a unique DIV ID so each instance of my block will require this ID.
I have included my JS file inside the enqueue_assets and used 'wp_add_inline_script' to send the unique ID to this.
My problem is with 'render_template' as I cannot send the same unique ID across. I have tried using the attributes inside 'render_template' but if I do this then I cant send this across to JS.
I have tried various options but no luck, below is just an example so you get the idea of what I am trying to achieve. I was just wondering if I was missing something obvious?
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', 'enqueue_style' => plugin_dir_url( __FILE__ ) . 'css/splide.min.css', 'enqueue_script' => plugin_dir_url( __FILE__ ) . 'js/splide.min.js', 'supports' => [ 'align' => ['wide', 'full'], ], 'enqueue_assets' => function() { wp_enqueue_script( 'splide-custom-script', plugin_dir_url( __FILE__ ) . 'js/splide-run.js', [], '1', true ); wp_add_inline_script( 'splide-custom-script', 'const splideSettingsPHP = ' . json_encode( array( 'uniqueTargetID' => $uniqueID, 'is_preview' => $is_preview, 'autoplay' => $autoplay, ) ), 'before' ); }, 'keywords' => ['carousel', 'product', 'listing', 'ecommerce'], 'multiple' => false, 'reusable' => false, 'preview' => [ 'image' => '', // Image ID 'title' => 'Carousel', 'description' => 'Carousel with product support', ], 'fields' => [ [ ...
March 14, 2022 at 10:30 PM #34515Long Nguyen
ModeratorHi Nick,
You can access the block ID via
$attributes['id']
in the callback function or template.
https://docs.metabox.io/extensions/mb-blocks/#render_callbackAnd please notice that the ID of the block changes every time updating the post or refresh the editing page, be careful if you use the ID to style the element or use it as a selector.
In your case, I will inform the development team to consider supporting inline script in the template to execute JS functions.
March 14, 2022 at 11:48 PM #34518Nicholas Cox
ParticipantHi
Ok thanks, well I thought about using $attributes['id'] as it would work for my case; as its just for JS function purposes. It would be a useful if there was a way to pass the $attributes['id'] inside Javascript.
Thanks
-
AuthorPosts
- You must be logged in to reply to this topic.