Twig conditional statement if block is present in Drupal 8
The situation:
- I have a block. It has a machine name. my-block
- I have a region. It has a name. my-region.
- I have some other random element. my-element
- I am NOT working in region.html.twig. I am working in page.html.twig
- 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.

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