How to use views_embed_view() in drupal 8, 9 & 10 [solved]

In some cases you want to embed a view inside your custom module. The views_embed_view() function is the way to go. With this little snippet, you can render any view:

Early Drupal 8

$result = render(views_embed_view('submenu', 'block_1'));
print $result;

In this case, "submenu" is the name of my view and "block_1" is the display id. For more examples, take a look at the function page.

update: 06/19/2019

It is also possible to load your view programmatically and display it in twig: https://stefvanlooveren.me/blog/get-views-row-count-twig-drupal-8

Drupal 8, 9 & 10

$view = \Drupal\views\Views::getView('submenu');
$view->setDisplay('block_1');
$view->execute();
$result = $view->buildRenderable('block_1', $view->args);
$output = \Drupal::service('renderer')->render($result);
print $output;

Here, we are using the buildRenderable() method to generate a renderable array for the block_1 display of the submenu view. Then, we are using the renderer service to render the output of the view as HTML.

Please note that the Views class is available in the views module, which needs to be installed and enabled on your Drupal site before you can use this code.