You are here

public static function MenuBlockTitle::preRender in Menu block title 8

The preRender callback which modifies the build output.

File

src/MenuBlockTitle.php, line 22

Class

MenuBlockTitle
Provides methods for preRender hook.

Namespace

Drupal\menu_block_title

Code

public static function preRender($build) {
  if (!isset($build['#derivative_plugin_id'])) {
    return $build;
  }
  $menu_name = $build['#derivative_plugin_id'];
  $active_menu_item = \Drupal::service('menu.active_trail')
    ->getActiveLink($menu_name);
  if (!$active_menu_item) {
    return $build;
  }

  // If a parent exists, load and use as title.
  if ($active_menu_item
    ->getParent()) {
    $parent_uuid = str_replace('menu_link_content:', '', $active_menu_item
      ->getParent());
    $parent = \Drupal::service('entity.repository')
      ->loadEntityByUuid('menu_link_content', $parent_uuid);
    $linked_title = [
      '#type' => 'link',
      '#url' => $parent
        ->getUrlObject(),
      '#title' => $parent
        ->getTitle(),
    ];
  }
  else {
    return $build;
  }
  $build['#configuration']['label'] = $linked_title;
  return $build;
}