Check if empty region failed 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')-&gt;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 ?
In theming the use of render() is correct, you can't use a different render method. The problem is that many blocks are placeholdered and you can't determine at the point the page template is rendered in which context the placeholdered block might be rendered in future. Probably then with a different user logged in because blocks cached per user are placeholdered by default.
The code in your question thinks the region is empty because striptags removes placeholders which usually are formatted as HTML tag.
You can change this at the expense of cache performance by adjusting the cacheablity of the blocks involved or customizing the auto-placerholder condition site-wide.
See https://www.drupal.org/docs/8/api/render-api/auto-placeholdering