Skip to content

Instantly share code, notes, and snippets.

@gonssal
Last active March 4, 2020 20:44
Show Gist options
  • Save gonssal/c63c43e0c9a21e01eefb00e8aa5a1694 to your computer and use it in GitHub Desktop.
Save gonssal/c63c43e0c9a21e01eefb00e8aa5a1694 to your computer and use it in GitHub Desktop.
Drupal 8 code to mark as active all the menu links poiting to /user when viewing an user's own profile.
/**
* Implements hook_preprocess_HOOK().
*
* @note: This can be removed if https://www.drupal.org/project/drupal/issues/2870054 is fixed.
*/
function MODULE_preprocess_menu(&$variables) {
/** @var Drupal\Core\Routing\CurrentRouteMatch */
$routeMatcher = \Drupal::routeMatch();
/** @var Drupal\Core\Routing\RouteMatch */
$currentRouteMatch = $routeMatcher->getCurrentRouteMatch();
if ($currentRouteMatch->getRouteName() === 'entity.user.canonical') {
/** @var \Drupal\Core\Session\AccountProxyInterface */
$currentUser = \Drupal::currentUser();
if ($currentUser->isAuthenticated() && $currentUser->id() === $currentRouteMatch->getParameter('user')->id()) {
foreach ($variables['items'] as $name => $item) {
MODULE_set_user_profile_link_as_active($variables['items'][$name]);
}
}
}
}
/**
* Sets a menu item's link as active if it's to the user page.
*
* @param array $item
* An array of menu items.
*/
function MODULE_set_user_profile_link_as_active(array &$item) {
if (isset($item['url']) && $item['url']->getRouteName() === 'user.page') {
$item['in_active_trail'] = TRUE;
}
if (!empty($item['below'])) {
foreach ($item['below'] as $name => $below_item) {
MODULE_set_user_profile_link_as_active($item['below'][$name]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment