In Drupal 7, we were able to render the main navigation menu onto a page outside the main Drupal folders by including bootstrap.inc and displaying it with this code.

 $menuData = menu_tree_output(menu_tree_all_data('main-menu'));
 print drupal_render($menuData); 

Can something similar be done in Drupal 8?


Here is how to get the render Array :

  $menuService = \Drupal::service('menu.link_tree');
  $parameters = $menuService->getCurrentRouteMenuTreeParameters('main');
  $mainMenutree = $menuService->load('main', $parameters);
  $renderArray = $menuService->build($mainMenutree);

If needed, here is how to generate the HTML

$html = \Drupal::service('renderer')->render($renderArray);

Note : replace 'main' by menu name for another one.

  • Sweet! Thank you! I really appreciate it. – johnnyeng Feb 8 '19 at 17:30
  • ! Alas, I can't seem to get it to work though. I'm calling bootstrap.inc like this: use Drupal\Core\DrupalKernel; use Drupal\Core\Form\EnforcedResponseException; use Drupal\Core\Url; use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Drupal\Core\Site\Settings; // Change the directory to the Drupal root. chdir('..'); $autoloader = (require_once './core/includes/bootstrap.inc'); Is there something else needed? JE – johnnyeng Feb 8 '19 at 17:40
  • None of this is needed, the piece of code i gave you is enough, where are you doing this ? – Oulalahakabu Feb 11 '19 at 8:44
  • Hello. In a directory outside of the main Drupal 8 folder structure. Thank you! @Oulalahakabu – johnnyeng Feb 11 '19 at 15:45

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.