Render a Drupal 9 View programmatically (Render arrays FTW!)
Steven Jones
Senior Developer
Hey, you seem to look at this article a lot! Why not Bookmark this article so you can find it easily in the future?
Extra quick tip for developers working with Drupal 8 or 9: Adding views to your page content is now incredibly straightforward:
$content['editor_tools']['view'] = [
'#type' => 'view',
'#name' => 'editor_tools',
'#display_id' => 'embed',
'#arguments' => [
123,
],
];
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);