Hide a view if there are no results (Spin-off of Remove/Hide the block if the View is empty?. I find the other question a bit confusing, and want to reduce it to the essential question.)

When rendering a view programmatically, and there are no results, there is still some HTML returned from $view-&gt;render().

This can be desirable in the following cases:


There is a "No results behavior".
There are exposed filters, which need to be shown independent of the view result.
The view is using AJAX, so it could happen that new content appears dynamically.
Perhaps other reasons?


I want to write generic code that renders a view, but completely hides it if there are no results, and no other reason to show it.

So far I have this:

$view = \views_get_view($view_name);
if (NULL === $view) {
  return [];
}
$success = $view-&gt;set_display($display_id);
if (FALSE === $success) {
  return [];
}
$view-&gt;set_arguments($args);
// See https://www.drupal.org/node/525592#comment-1833824
$view-&gt;override_path = $_GET['q'];

$view-&gt;pre_execute();
$view-&gt;execute();

if (empty($view-&gt;result) &amp;&amp; empty($view-&gt;empty)) {
  // @todo Also check for exposed filters!
  return [];
}

$markup = $view-&gt;render();

$view-&gt;post_execute();

if (FALSE === $markup) {
  return [];
}
return ['#markup' =&gt; $markup];


So the question is: Which other checks should I add when looking if the view is empty? (the place with the @todo).

How do I check if there are exposed filters?
Which other criteria are relevant?
Considering how many criteria might have to be considered to determine if a view can be hidden, I decided to make this a configuration option instead.

I see two ways to do this:


The component where the view is embedded can have a configuration option "Hide view if no results". This is what I went with.
One could make a symbolic views plugin for "no results behavior", named "Hide view if no results". Then one could implement e.g. hook_preprocess_views_view(), or possibly another hook, to hide the view if the new no results behavior is present.


I could write a lot more details, but for now I want to share the ideas behind these options, maybe this already helps.

I am marking this as the accepted answer. But if someone can come up with something more convincing, I will change it.