Skip to main content

Render a Drupal 8 View programmatically (Render arrays FTW!)

12th Mar 2018

Steven Jones

Senior Developer

Extra quick tip for Drupal developers: Adding views to your page content is now incredibly straightforward:

$content['editor_tools']['view'] = [
  '#type' => 'view',
  '#name' => 'editor_tools',
  '#display_id' => 'embed',
  '#arguments' => [

And that's it! $content is my render array which I'll return and let Drupal render. I suspect most of the bits there are self-explanatory, but in case they aren't:

  • '#type' => 'view' is the magic that lets Drupal's rendering system know that this array represents a view to render.
  • '#name' is the machine name of the view you want to render.
  • '#display_id' is the display ID within the view to render.
  • '#arguments' is an optionally array of arguments to pass to the view.

If you want it even easier than that, then using the views_embed_view() function will return you the render array and complete access checks etc:

$content['editor_tools']['view'] = views_embed_view('editor_tools', 'embed', 123);