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

Parent Feed: 

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);

Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web