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');
    // contextual relationship filter
    $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?

Buy me a drink 🍺 to keep me motivated to create free content like this!