Add body class if a block is present I need to add a body class if a block or menu is present on the current page on Drupal 8. Probably this should be done on template_preprocess_page() or template_preprocess_html().
A block is visible in a page depending on two conditions:


None of the condition plugins associated to the block marks the block as not visible
The current user has the permission to see the block


Assuming the block is visible at a specific path is wrong because the current user could simply not have the permission to view it. Adding to that the fact that any third-party modules could define new condition plugins, the only way to avoid duplicating in code the block settings done from the user interface is using code similar to the following one.

function mymodule_preprocess_html(&amp;$variables) {
  // Replace 'block_id' with the ID of your block.
  $block = Block::load('block_id');
  if ($block &amp;&amp; $block-&gt;access('view')) {
    // The block is visible to the current user.
    // Replace 'the-class-to-add' with your CSS class.
    $variables['attributes']['class'][] = 'the-class-to-add';
  }
}


Remember to add the correct use statements on the top of the file containing that code (e.g. use Drupal\block\Entity\Block; to be able to access the block entity class).