I try to check if my sidebar second if empty. If it is not empty, I add a class col-md-8
on my section-main
.
To check if the sidebar is empty I use this code in the page.html.twig template of my custon theme:
{% if page.sidebar_second and page.sidebar_second is not empty and
page.sidebar_second|render|striptags|trim is not empty %}
My problem is that sometimes the sidebar second if considered as empty but it is not. In the sidebar second, I have a views block that the content depends on the current node taxonomy or book id. The query to get the content of this views block if altered in my_custom_module_views_query_alter(ViewExecutable $view, QueryPluginBase $query)
function.
When I checked for sidebar_second in page.html.twig, the content of this block is always empty, but if I have another block in sidebar_second (so the column is displayed), this block has actually some content and is displayed.
So to check if my sidebar is really empty or not, I tried to check that in the my_custom_theme_preprocess_page()
function in my_custom_theme.theme, like this :
$rendered_sidebar_second = \Drupal::service('renderer')->renderRoot($variables['page']['sidebar_second']);
$with_sidebar_second = !empty(trim(strip_tags($rendered_sidebar_second)));
$variables['with_sidebar_second'] = $with_sidebar_second;
Then , in my page.html.twig, I check the variable with_sidebar_second
to know if sidebar_second is empty o not. This gives the right results, but induces a problem for assets : PHP Exception LogicException: 'A stray renderRoot() invocation is causing bubbling of attached assets to break.. Using renderPlain()
gives the same result. Using render($variables['page']['sidebar_second'], false)
does not give the good result.
Is there a solution to have the good result for the sidebar_second and have all assets too ?