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!

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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