I Heart Technology Blog

by Nyberg Technology


Druapl 7 Dropdown Menu Using Twitter Bootstrap

by Darryn Nyberg

Resources > Dec 17, 2017


At long last the Twitter Bootstrap dropdown menu in Drupal 7. I have been attempting to do this for a while but could never get it to work because I was working with the wrong theme elements. Here we implemented the Twitter Bootstrap drop down menu within the Drupal 7 hook_menu_link using a pile of "if" functions. This is inspired by the Twitter Bootstrap theme on drupal.org.

To use, place the blow code in your themes template.php file and change the to the name of your theme.


_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  
  if ($element['#below']) {

    // Prevent dropdown functions from being added to management menu as to not affect navbar module.
    if (($element['#original_link']['menu_name'] == 'management') && (module_exists('navbar'))) {
      $sub_menu = drupal_render($element['#below']);
    }

    else {
      // Add our own wrapper
      unset($element['#below']['#theme_wrappers']);
      $sub_menu = '';
      $element['#localized_options']['attributes']['class'][] = 'dropdown-toggle';
      $element['#localized_options']['attributes']['data-toggle'] = 'dropdown';

      // Check if this element is nested within another
      if ((!empty($element['#original_link']['depth'])) && ($element['#original_link']['depth'] > 1)) {
        // Generate as dropdown submenu
        $element['#attributes']['class'][] = 'dropdown-submenu';
      }
      else {
        // Generate as standard dropdown
        $element['#attributes']['class'][] = 'dropdown';
        $element['#localized_options']['html'] = TRUE;
        $element['#title'] .= ' ';
      }

      // Set dropdown trigger element to # to prevent inadvertant page loading with submenu click
      $element['#localized_options']['attributes']['data-target'] = '#';
    }
  }
 // Issue #1896674 - On primary navigation menu, class 'active' is not set on active menu item.
 // @see http://drupal.org/node/1896674
 if (($element['#href'] == $_GET['q'] || ($element['#href'] == '' && drupal_is_front_page())) && (empty($element['#localized_options']['language']) || $element['#localized_options']['language']->language == $language_url->language)) {
   $element['#attributes']['class'][] = 'active';
 }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
  • ' . $output . $sub_menu . "
  • \n"; } ?>

    About

    The I Heart Technology Blog is written by our team members at Nyberg Technology and NyTechEd.

    We hope to educate and support the community through providing resources and premium software development.

    Become A Team Member

    Are you a developer? Are you a tech blogger? We would love to hear from you!

    (559) 335-3556

    info@nybergtechnology.com
    Nyberg Technology
    516 Villa, #13
    Clovis, CA. 93612