1

I want to display the whole menu tree in my Drupal 8 theme to be able to show/hide submenus using javascript. To accomplish that, I added the following code to my theme file:

function pspartner_preprocess_page(&$variables) {

  $menu_tree = \Drupal::menuTree();
  $menu_name = 'main';

  // Build the typical default set of menu tree parameters.
  $parameters = new MenuTreeParameters();

  // Load the tree based on this set of parameters.
  $tree = $menu_tree->load($menu_name, $parameters);

  // Transform the tree using the manipulators you want.
  $manipulators = array(
    // Only show links that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    // Use the default sorting of menu links.
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  );
  $tree = $menu_tree->transform($tree, $manipulators);

  // Finally, build a renderable array from the transformed tree.
  $menu = $menu_tree->build($tree);

  // Make menus available in templates
  $variables['main_menu_tree'] = $tree;
  $variables['main_menu'] = $menu;
}

This works, but the active trail is not set.

0

Set the active trail in the MenuTreeParameter object per MenuTreeParameters::setActivityTrail. This requires knowing the menu link plugin ids, which can be retrieved using MenuActiveTrail::GetActiveTrailIds (linked from the previous API page).

  $active_trail = \Drupal::service('menu.active_trail');

  // Build the typical default set of menu tree parameters.
  $parameters = new MenuTreeParameters();
  $parameters->setActiveTrail($active_trail->getActiveTrailIds($menu_name));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.