2

I have a region page_intro where I display a view, with some CSS on it. When the view is empty (return no result), the region is still displayed (All html code before and after {{ page.page_intro }}). Is there a way to compltetly remove it when the view is empty ?

template :

{% if page.page_intro %}
    {# #page-intro #}
    <div id="page-intro" class="clearfix">
        <div class="container-fluid">
            <div class="row">
                {# #page-intro-inside #}
                <div id="page-intro-inside" class="col-md-10 col-md-offset-1 clearfix">
                    {{ page.page_intro }}
                </div>
                {# EOF: #page-intro-inside #}
            </div>
        </div>
    </div>
    {# EOF: #page-intro #}
{% endif %}

I'm on Drupal 8.2.0 version.

0

I would suggest you use the views template for your view (views-view--page-intro.html.twig, and put the wrapping markup in there, rather than in the page template.

{% if rows %}
    <div id="page-intro" class="clearfix">
        <div class="container-fluid">
            <div class="row">
                <div id="page-intro-inside" class="col-md-10 col-md-offset-1 clearfix">
                    {{ rows }}
                </div>
            </div>
        </div>
    </div>
  {% endif %}

turn on twig debugging to see the template suggestions in your page markup. this will be the default.services.yml file in your config directory where you have settings.php

 twig.config:
    debug: true
0

You could do it purely with CSS, just make it so the region itself only gets its width/height from the views rows.

You could also set the region to "display:none;" then use Javascript to detect if there's any views rows and change the display if it finds one.

I'm not sure if there's a simple solution in PHP. You could recreate the views db query in your theme's preprocessing, and use that to hide the region if it doesn't find any results.

0

I'd do it like this. Example below is used for node templates:

use \Drupal\views\Views;

function MYTHEME_preprocess_node(&$variables) {
  // make the result count available as a variable for a certain content type
  if($node->getType() == 'news') {
    $view = Views::getView('related_news');
    $view->setDisplay('default');
    // contextual relationship filter
    $view->setArguments([$variables['node']->id()]);
    $view->execute();
    $variables['related_news'] = $view->render();
  }
}

Then, in your node

{% if related_news_count > 0 %}
  // Region stuff here 
{% endif %}

https://stefvanlooveren.me/blog/get-views-row-count-twig-drupal-8

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.