Check if block is enabled for current page?

Created on 18 December 2016, about 8 years ago
Updated 10 July 2024, 6 months ago

I'm currently printing a block in my region.html.twig using for example
{{ drupal_block('bartik_powered') }}

Can I somehow only show the block on pages for which it is enabled in the Block Layout page?

I tried

{% if drupal_block('bartik_powered') %}
  {{ drupal_block('bartik_powered') }}
{% endif %}

But that if-condition seems to return TRUE for every page, not just for the 5-6 pages the block is enabled on.

💬 Support request
Status

Fixed

Version

1.0

Component

Miscellaneous

Created by

🇧🇪Belgium Puppetmast0r

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • leymannx Berlin

    Seems only enabled blocks have a weight, so I did it like this:

    {% if drupal_entity('block', 'volcano_search_autocomplete')['#weight'] is defined %}
      ...
    {% endif %}
    
  • Thanks @leymannx,
    I face the same issue, and the solution is what you said: the array returned in drupal_entity('block', 'mytheme_my_block_id') is a bigger array when enabled than disabled.

    Here is an example dump (with my custom 2 menus):

    // Disabled block
    ^ array:1 [▼
      "#cache" => array:3 [▼
        "contexts" => array:2 [▼
          0 => "url.path"
          1 => "languages:language_interface"
        ]
        "tags" => array:1 [▼
          0 => "config:block.block.menushop"
        ]
        "max-age" => -1
      ]
    ]
    
    // Enabled block
    ^ array:3 [▼
      "#cache" => array:4 [▼
        "keys" => array:3 [▼
          0 => "entity_view"
          1 => "block"
          2 => "menuprincipal"
        ]
        "contexts" => array:3 [▼
          0 => "languages:language_interface"
          1 => "route.menu_active_trails:main-menu"
          2 => "url.path"
        ]
        "tags" => array:3 [▼
          0 => "block_view"
          1 => "config:block.block.menuprincipal"
          2 => "config:system.menu.main-menu"
        ]
        "max-age" => -1
      ]
      "#weight" => -16
      "#lazy_builder" => array:2 [▼
        0 => "Drupal\block\BlockViewBuilder::lazyBuilder"
        1 => array:3 [▼
          0 => "menuprincipal"
          1 => "full"
          2 => null
        ]
      ]
    ]
    

    I don't know on what I'd rather do the condition:

    • Check the size of the array?
    • Check the definition of '#weight' and '#lazy_builder' ?

    We don't know how that will evolve, so that's why it will be better to have a true boolean value to indicate this status.

    What do we do now?

Production build 0.71.5 2024