Menu does not set active trail when generating tree in theme file 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(&amp;$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-&gt;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' =&gt; 'menu.default_tree_manipulators:checkAccess'),
    // Use the default sorting of menu links.
    array('callable' =&gt; 'menu.default_tree_manipulators:generateIndexAndSort'),
  );
  $tree = $menu_tree-&gt;transform($tree, $manipulators);

  // Finally, build a renderable array from the transformed tree.
  $menu = $menu_tree-&gt;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.
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-&gt;setActiveTrail($active_trail-&gt;getActiveTrailIds($menu_name));