5

I need to create block with a list of links menu child items (only first level) of a given menu like this:

  • Item 1
  • Item 2
  • Item 3

With this code I can have the menu items but I don't know how to process each element to obtain the menu item title and the menu item url.

$menu_name = 'main';
$menu_tree = \Drupal::menuTree();
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
$parameters->setMinDepth(0);

$tree = $menu_tree->load($menu_name, $parameters);
$manipulators = array(
  array('callable' => 'menu.default_tree_manipulators:checkAccess'),
  array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
);
$tree = $menu_tree->transform($tree, $manipulators);
1

1 Answer 1

14

I found the answer based in this question: How to turn a menu tree into an associative array?

You can use each array element as a item of MenuLinkInterface

To see others parameters check the class MenuTreeParameters

<?php
/**
 * @file
 * Contains \Drupal\YOUR_MODULE\Plugin\Block\SectionsFooter.
 */

namespace Drupal\YOUR_MODULE\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Link;

/**
 * Provides a 'SectionsFooter' block.
 *
 * @Block(
 *   id = "sections_footer",
 *   admin_label = @Translation("Sections"),
 *   category = @Translation("YOUR_MODULE")
 * )
 */
class SectionsFooter extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $menu_name = 'main';
    $menu_tree = \Drupal::menuTree();
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $parameters->setMinDepth(0);
    //Delete comments to have only enabled links
    //$parameters->onlyEnabledLinks();

    $tree = $menu_tree->load($menu_name, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $tree = $menu_tree->transform($tree, $manipulators);
    $list = [];

    foreach ($tree as $item) {
      $title = $item->link->getTitle();
      $url = $item->link->getUrlObject();
      $list[] = Link::fromTextAndUrl($title, $url);
    }

    $output['sections'] = array(
    '#theme' => 'item_list',
    '#items' => $list,
    );
    return $output;
  }
}

References:

Menu tree building is now a service

3
  • I want to do the same in my theme. is this possible?
    – siddiq
    Commented Dec 11, 2017 at 0:33
  • @siddiq yes, is possible. Commented Dec 11, 2017 at 3:34
  • I tried to use MY_THEME instead of YOUR_MODULE in the above code? But that doesn't work. Would you please explain how to do that? May be i should post this as separate question.
    – siddiq
    Commented Dec 11, 2017 at 3:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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