Skip to main content

Drupal 9 twig: How to tell that a region is indeed empty

When you are building a new custom theme and you want to make sure that you do not end up with empty rendered regions that might mess up with your layout styling (a nice bootstrap grid for example). Usually, you end up with something like this:

{% set slider_rendered = page.slider|render %}
{% if slider_rendered|striptags('<drupal-render-placeholder><img><video><[...]>')|trim is not empty %}
  <div class="slider slider--region">
    {{ slider_rendered }}
{% endif %}

and this works as expected.


Recently, I discovered that there is a nice module for this : The twig_real_content module adds a new twig filter: real_content, that you can use instead of the big if is not empty condition above.

{% set sidebar_first_rendered = page.sidebar_first|render %}
{% if sidebar_first_rendered|real_content is not empty %}
  <div class="sidebar sidebar--first">
    {{ sidebar_first_rendered }}
{% endif %}

Well done, guys!

theme subtheme theming