I'm on Drupal 8,

I'm using \Drupal::entityQuery('block') to get the list of blocks.

Now I want to determine if the block is visible for:

  • Current Page (Content Type)
  • Current User (Role)
  • Current Path

I want this information according to visibility settings configured in block's configuration.

I can use $block->getVisibility() method when I load the block and there I can iterate through visibility settings and find out if the block is visible or not.

I wander if there is a better and easier way to do this??


Checking view access to a block includes visibility checks. so you can just do this: if ($block->access('view')).

Why do you want this information? block.module has a block.repository service with a getVisibleBlocksPerRegion() which gives you exactly that. a list of visible blocks, grouped by region.

  • Hi @Berdir, Thank you for your answer, it worked and did what I wanted :) The reason I'm doing this is that I have some blocks I want to print in {{ page_bottom }} not in a region. I need this because I want to have functionality where users will be able to embed third party services at the bottom of the page. – otarza Jan 5 '16 at 7:34
  • 2
    I see. Not sure about your structure, but by default, page_bottom is immediately after page. So why not just make a block region that's at the end of page.html.twig and place your blocks there? – Berdir Jan 5 '16 at 9:30
  • Good point, I thought about that but we had a requirement in which user doesn't have to add region manually. If user installs module it should work without adding a new region. – otarza Jan 6 '16 at 8:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.