How to render a views programmatically in drupal 8?

Public

Differente ways to render a views programmatically in drupal 8

</> CopyGet raw version
php
  1. // Drupal 7
  2. views_embed_view('content', 'page_1');
  3.  
  4. // Drupal 8
  5. // -------
  6.  
  7.  
  8. // drupal_render will be deprecated soon see https://api.drupal.org/api/drupal/core!includes!common.inc/function/drupal_render/8
  9. drupal_render(views_embed_view('content', 'page_1'));
  10.  
  11. // Another option to render it (much better)
  12. \Drupal::service('renderer')->render(views_embed_view('content', 'page_1'));
  13.  
  14.  
  15. // BEST OPTION by injecting the service dependency instead "renderer".
  16. // -------------------------------------------------------------------
  17.  
  18. use Drupal\Core\Controller\ControllerBase;
  19. use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
  20. use Symfony\Component\DependencyInjection\ContainerInterface;
  21. use Drupal\Core\Render\Renderer;
  22.  
  23. class DefaultController extends ControllerBase implements ContainerInjectionInterface {
  24.  
  25. protected $renderer;
  26. public function __construct(Renderer $renderer) {
  27. $this->renderer = $renderer;
  28. }
  29.  
  30. public static function create(ContainerInterface $container) {
  31. return new static(
  32. $container->get('renderer')
  33. );
  34. }
  35. public function page() {
  36.  
  37. $content['#markup'] = $this->renderer->render(views_embed_view('content', 'page_1'));
  38. return $content;
  39. }
  40. }