When using twig, sometimes you would like to know whether the view has results or not. This snippet shows you how.

First, in your mytheme.theme file use this preprocess function:

// snippet: https://stefvanlooveren.me/node/69
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_count'] = count($view->result);
    $variables['related_news'] = $view->render();
  }
}

Then, in your twig file f.e. node--news--full.html.twig you have everything available:

{% if related_news_count > 0 %}
  <h2>Related news</h2>
  {{ related news }}
{% endif %}

 


Saved you some valuable time?

Donate and get more free time-saving code on this website in the future.