Get current view object from route object

Posted by patrick on Sun, 01/29/2017 - 13:26

Sometimes you want to get the view object from a route object. In the following example, we'll implement a preprocess function for the page template to get the view object associated with the current route object, if any, and then get the title of the current display from that view object. We'll provide this title as a template variable to our template.

use Drupal\views\Views;
 * Implements hook_preprocess_HOOK() for page.html.twig.
function example_preprocess_page(array &$variables) {
  $variables['view_title'] = '';
  // Get current route object.
  $route = \Drupal::routeMatch()->getRouteObject();
  if ($route) {
    // Get view id and display id from route.
    $view_id = $route->getDefault('view_id');
    $display_id = $route->getDefault('display_id');
    // If you just want the page title, you could get it directly from the 
    // route object. Unfortunately, it will be untranslated, so if we want
    // to get the translated title, we still need to load the view bject.
    // $route->getDefault('_title');
    if (!empty($view_id) && !empty($display_id)) {
      // Get the view by id.
      $view = Views::getView($view_id);
      if ($view) {
        // Set display id.
        // Get translated title.
        $variables['view_title'] = $view->getTitle();

First, we'll get a route match object and get the actual route object from that object. This will be the route object for the route, that is currently active. Once we have the route object, we can take advantage of the various defaults, that views sets on the routes, it provides. That way, we can get the view id and display id associated with that route. Check out PathPluginBase::getRoute for more defaults and options added to the route, if you need something more obscure ;).

Once we have a view id and a display id, it's quite easy to load the view object from storage by id and to set the display by display id. Since in this example, we're interested in the title of the view, we'll finally call the getTitle() method of the view object to get the title of the display.

Drupal 8