Created
April 13, 2018 17:32
-
-
Save mrtag23/9cefb3a696ad7cba38673f71e968177c to your computer and use it in GitHub Desktop.
Drupal 8 - Set active class name for active link.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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