Twig conditional statement if block is present in Drupal 8

Sarah Carney
Jul 27, 2017 · 2 min read

The situation:

  1. I have a block. It has a machine name. my-block
  2. I have a region. It has a name. my-region.
  3. I have some other random element. my-element
  4. I am NOT working in region.html.twig. I am working in page.html.twig
  5. How do I show my-element IF my-block is present in my-region?

Thanks to help from markconroy in the Drupaltwig Slack channel, I have learned how.

In page.html.twig…

{# Only show my-element if my-block is present in my-region #}
{% if page.my-region.my-block %}
my-element
{% endif %}

My specific use case is that my search toggle button, which show/hides a search field on mobile, really needs to live far away from the actual search field in the mark-up.

It is possible that a client would opt not to have the specific Search block in the header. If there is no search there should be no search toggle.

With this method, I can use a conditional statement to only show my search toggle if the block is enabled.


How to get the machine name of the region: mytheme.info.yml

regions:
header_first: "Header First"
header_second: "Header Second"

Etc, where header_first is the machine name and Header First is the display name.

How to get the machine name of the block: Structure > Block Layout

‘Configure’ the block. The machine name is to the right of the Title field.

The machine name is to the right of the Title field

Always very happy to hear about other ways to do this, or other fun use cases.

Sarah Carney

Written by

I’m a front-end developer and web designer and love to code a lot.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade