Skip to content

Instantly share code, notes, and snippets.

@mrtag23
Created April 13, 2018 17:32
Show Gist options
  • Save mrtag23/9cefb3a696ad7cba38673f71e968177c to your computer and use it in GitHub Desktop.
Save mrtag23/9cefb3a696ad7cba38673f71e968177c to your computer and use it in GitHub Desktop.
Drupal 8 - Set active class name for active link.
function theme_preprocess_menu(&$variables, $hook) {
if ($hook == 'menu') {
$current_path = \Drupal::request()->getRequestUri();
$items = $variables['items'];
foreach ($items as $key => $item) {
// Set active to dom element if path of menu item matches current path
if ($item['url']->toString() == $current_path) {
// Add active link.
$variables['items'][$key]['attributes']['class'][] = 'active';
} else {
// Set active to dom element if path of menu item matches first part of current path
$url_fragments = explode('/', $current_path);
if (count($url_fragments) > 1 AND '/' . $url_fragments[1] == $item['url']->toString()) {
$variables['items'][$key]['attributes']['class'][] = 'active';
}
}
}
}
}
// $variables['items'][$key]['attributes']['class'][] = 'active';
// set to
// $variables['items'][$key]['attributes']->addClass('active');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment