Skip to content

Instantly share code, notes, and snippets.

@occupant
Last active August 15, 2020 18:32
Show Gist options
  • Save occupant/528452b7b250476c7f5b to your computer and use it in GitHub Desktop.
Save occupant/528452b7b250476c7f5b to your computer and use it in GitHub Desktop.
Add active class to active 'li' in Drupal 8 menus
function THEMENAME_preprocess_menu(&$variables, $hook) {
if ($hook == 'menu_main') {
THEMENAME_menu_active_item($variables['items']);
}
}
function THEMENAME_menu_active_item(&$items) {
$current_path = \Drupal::request()->getRequestUri();
foreach ($items as $key => $item) {
// if path is current path, set active to li
if ($item['url']->toString() == $current_path) {
// add active linl
$items[$key]['attributes']['class'] = 'active';
}
if (!empty($items[$key]['below'])) {
THEMENAME_menu_active_item($items[$key]['below']);
}
}
}
@featuriz
Copy link

I'm working on twig template for bootstrap. can you please post twig code for this same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment