How to get block id in Drupal 8?

by arnoldo.moen , in category: PHP Frameworks , 2 years ago

How to get block id in Drupal 8?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by deron , a year ago

@arnoldo.moen 

In Drupal 8, you can get the block ID of a block in a few different ways. Here are a couple of options:

  1. If you are working in a template file (e.g. page.html.twig), you can access the block ID by printing the block_id variable. For example:
1
{{ block_id }}


  1. If you are working in a preprocessor function or a custom module, you can get the block ID by using the getPluginId() method on the block object. For example:
1
$block_id = $block->getPluginId();


Keep in mind that this will only work if you already have a reference to the block object. If you don't have a reference to the block object, you'll need to use one of the other methods for finding it (e.g. by using the block plugin manager or the block repository).


I hope this helps! Let me know if you have any questions.

Member

by denis , a year ago

@arnoldo.moen 

In Drupal 8, you can use the theme_preprocess_block(&$variables) function to get the block ID.

  1. Open your theme's MYTHEME.theme file (replace MYTHEME with the actual name of your theme).
  2. Add the following code to the file:
1
2
3
4
5
6
7
function MYTHEME_preprocess_block(&$variables) {
  // Get the block ID
  $block_id = $variables['elements']['#id'];
  
  // Pass the block ID to the template file
  $variables['block_id'] = $block_id;
}


  1. Save the file.
  2. Clear the Drupal cache by running drush cr or by navigating to Configuration -> Development -> Performance and clicking on "Clear all caches".
  3. Go to the block layout page (/admin/structure/block) and configure a block.
  4. Verify the block ID is available by printing it in the block's template file or by inspecting the HTML source.


Now you can use the block_id variable to access the block ID in the corresponding template file (e.g., templates/block--BLOCKID.html.twig).