diff --git a/core/includes/menu.inc b/core/includes/menu.inc index ab14b9b753..fc69ee4cc3 100644 --- a/core/includes/menu.inc +++ b/core/includes/menu.inc @@ -11,6 +11,7 @@ */ use Drupal\Component\Render\FormattableMarkup; +use Drupal\Core\Url; /** * Prepares variables for single local task link templates. @@ -77,6 +78,51 @@ function template_preprocess_menu_local_action(&$variables) { ]; } +/** + * Prepares variables for menu templates on the homepage. + * + * Default template: menu.html.twig. + * + * @param $variables + * An Associative array containing: + * - menu_name: The machine name of the menu. + * - items: A nested list of menu items. Each menu item contains: + * - attributes: HTML attributes for the menu item. + * - below: The menu item child items. + * - title: The menu link title. + * - url: The menu link url, instance of \Drupal\Core\Url + * - localized_options: Menu link localized options. + * - is_expanded: TRUE if the link has visible children within the current + * menu tree. + * - is_collapsed: TRUE if the link has children within the current menu tree + * that are not currently visible. + * - in_active_trail: TRUE if the link is in the active trail. + */ +function template_preprocess_menu(&$variables) { + if (!\Drupal::service('path.matcher')->isFrontPage()) { + return; + } + + $homepagePath = \Drupal::config('system.site')->get('page.front'); + $homepageUrl = \Drupal::service('path.validator')->getUrlIfValid($homepagePath); + if (!$homepageUrl instanceof Url) { + return; + } + + $validHomepageRoutes = ['', $homepageUrl->getRouteName()]; + foreach ($variables['items'] as $key => $item) { + /** @var \Drupal\Core\Url $url */ + $url = $item['url']; + if ( + $url instanceof Url && + $url->isRouted() && + \in_array($url->getRouteName(), $validHomepageRoutes, TRUE) + ) { + $variables['items'][$key]['in_active_trail'] = TRUE; + } + } +} + /** * Returns an array containing the names of system-defined (default) menus. */