0

I'm creating a node--page.html.twig and I'm using twig_tweak to help render a block for my sidebar to display the sub-menus. Is there a way to hide it if the page doesn't have any submenus?

Here's my code:

<div class="page-sidebar grid-3 alpha">
  <div class="sub-region page-sidebar clearfix widgets widget-sidebar">
    <div class="contextual-links-region panel-pane pane-menu-tree pane-main-menu">
    {{ drupal_entity('block', 'mainmenu', check_access=false) }}
  </div>
</div>

Is there some sort of if statement I could use to hide the block if the page has no submenu?

Thank you!

1 Answer 1

0

I generally handle this sort of thing like:

// First render my content and set it to a variable.
{% set submenu = drupal_entity('block', 'mainmenu', check_access=false)|render %}
// Next, check if the variable have content.
{% if submenu %}
  // If variable has content, render with wrapping div(s).
  <div class="my-wrapping-div">
    {{ submenu }}
  </div>
{% endif %}

It's important to render the submenu whether or not it has any displayable content to make sure it's cache settings are bubbled up.

Note: this will only work if whatever your rendering returns no html. If you're seeing some wrapping divs, etc return, but no content, you can alter your if statement like {% if submenu|striptags|trim %} to strip html and check for only content.

1
  • Hi sonfd! I was wondering if it's possible to display a specifc level of the menu using your method? I have some sidebars that's just displaying the title of the submenu because in my 'mainmenu' block Menu Levels is "initial visibility level: 3" and "Number of levels to display": 2. So pages that are in level-2 that don't have any level-3 links display nothing except the title. My partner made a post too: drupal.stackexchange.com/questions/298415/… Commented Nov 26, 2020 at 4:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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