I got the 2nd level main menu in a block in the sidebar, drupal 8 correctly hides the menu (and the block) when the user browses a page that is not in this menu, but the theme continues to show the empty region. The condition {% if page.region %} is true. is there any way to solve this problem?
4 Answers
It is better to use construction
{% if page.region|render|striptags|trim|length > 0 %} ... {% endif %}
So you can check if there is some content or not.
-
2Note: This will not work properly if a region contains only HTML tags, such as Search Facets that are completely made up of <select> options. The striptags call will remove everything from these regions, making them appear to be empty and preventing your facets from showing. Commented Jun 12, 2018 at 22:05
I you use menu_block module, this patch will fix the problem of a region showing up even when there are no subitems for a menu. Only tested on menu block version 8.x-1.5.
-
your patch work nice vs the 8.x-1.5. Have you open an issue on the module page?– xaaCommented Nov 8, 2018 at 19:22
You can use {% if page.region|render|striptags %}
to make sure the regions actually has content. See also the discussion here: [meta] Themes improperly check renderable arrays when determining visibility.
I did it this way to reduce the number of renders.
{% set render_sidebar_first = page.sidebar_first|render %}
{% if render_sidebar_first and render_sidebar_first|striptags|trim|length > 0 %}
{% block sidebar_first %}
<aside class="{{ sidebar_class }}" role="complementary">
{{ render_sidebar_first }}
</aside>
{% endblock %}
{% endif %}
{{ kint(page.region) }}
(devel kint module enabled). It seems not to be empty.