How To Access Block Directory Inside Gutenberg Block.js File?

Gutenberg editor bundled in version 5.0 has revolutionized the way we create content in WordPress website. If you want to learn how to create a custom Gutenberg block, you can visit this blog post and you can also follow the collection “Gutenberg Block Development” to see all blog posts related to Gutenberg Block Development.

Sometimes, we need to access the block directory url inside Gutenberg block.js file (see following scenario). Let’s say that inside the block folder you have an images folder containing logo.png image and you want to access that image inside the block.js file. In this blog post we will learn how to access the image inside images folder from block.js file.

Directory Structure (Scenario)

  • customblocks.php (main plugin file)
  • block (folder containing files and folders of custom block)
    • images (folder containing image)
      • logo.png (we need to access this image inside block.js file)
    • index.php (enqueue block asset files)
    • style.css (block styles)
    • block.js (register the custom block)

By default in WordPress we have access to the plugins_url() php method, but since it’s a PHP method so we can’t call it inside the block.js file. So the solution is that after en-queuing the block.js file inside the index.php file we will use the wp_localize_script() method with block.js handle and will pass on the URL of the images folder which can then be extracted inside the block.js file.

....
....
wp_enqueue_script(
	'coupon-card', // Handle.
	plugins_url( 'block.js', __FILE__ ), // Block.js: We register the block here.
	array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor', 'jquery' ), // Dependencies, defined above.
	filemtime( plugin_dir_path( __FILE__ ) . 'block.js' ) // filemtime — Gets file modification time.
);
wp_localize_script(
	'coupon-card',
	'js_data',
	array(
		'images_url' => plugins_url( 'images', __FILE__ )
	)
);
....
....

Now inside the block.js file we can extract the url as shown below:

var images_folder_url = js_data.images_url;
var logo_image_src = images_folder_url+'/logo.png';

I hope this little trick will be helpful in your Gutenberg Block Development.

Leave a Comment

Your email address will not be published. Required fields are marked *