function views_embed_view

Same name in other branches
  1. 9 core/modules/views/views.module \views_embed_view()
  2. 8.9.x core/modules/views/views.module \views_embed_view()
  3. 11.x core/modules/views/views.module \views_embed_view()

Embed a view using a PHP snippet.

This function is meant to be called from PHP snippets, should one wish to embed a view in a node or something. It's meant to provide the simplest solution and doesn't really offer a lot of options, but breaking the function apart is pretty easy, and this provides a worthwhile guide to doing so.

Note that this function does NOT display the title of the view. If you want to do that, you will need to do what this function does manually, by loading the view, getting the preview and then getting $view->getTitle().

Parameters

$name: The name of the view to embed.

$display_id: The display id to embed. If unsure, use 'default', as it will always be valid. But things like 'page' or 'block' should work here.

...: Any additional parameters will be passed as arguments.

Return value

array|null A renderable array containing the view output or NULL if the display ID of the view to be executed doesn't exist.

1 call to views_embed_view()
ModuleTest::testViewsEmbedView in core/modules/views/tests/src/Kernel/ModuleTest.php
Tests views.module: views_embed_view().

File

core/modules/views/views.module, line 732

Code

function views_embed_view($name, $display_id = 'default') {
    $args = func_get_args();
    // Remove $name and $display_id from the arguments.
    unset($args[0], $args[1]);
    $view = Views::getView($name);
    if (!$view || !$view->access($display_id)) {
        return;
    }
    return [
        '#type' => 'view',
        '#name' => $name,
        '#display_id' => $display_id,
        '#arguments' => $args,
    ];
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.