2

I want to load the menu items from the main menu in a other menu. I've read a dozen examples but I can't get it to render the items at all.

Here's my code from my_theme.theme

function my_theme_menu__secondary(&$menu, &$menu_name, &$suggestions) {
  $menu_name = 'main';
  $menu_tree = \Drupal::menuTree();
  $parameters = new \Drupal\Core\Menu\MenuTreeParameters();
  $parameters->onlyEnabledLinks();
//  $parameters->setMinDepth(2)();
//  $parameters->setMaxDepth(2)();

  $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[] = Drupal\Core\Link::fromTextAndUrl($title, $url);
  }

  return $list;
}

Heres my menu--secondary.html.twig

{% import _self as menus %}

{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if list %}
    {% for item in list %}
      {%
        set item_classes = [
          'expanded',
          'dropdown',
          item.in_active_trail ? 'active',
        ]
      %}
      {% if menu_level == 0  %}
        <li{{ item.attributes.addClass(item_classes) }}>
        <a href="{{ item.url }}">{{ item.title }}</a>
        </li>
      {% endif %}
    {% endfor %}
  {% endif %}
{% endmacro %}

Any help is appreciated :)

3
  • Hey hey, why don't you simply use a menu block? Or drupal.org/project/menu_block? You can simply place a menu multiple times on your page with just core blocks.
    – leymannx
    Jun 13, 2018 at 8:33
  • Because I need the menu to be displayed twice, once with menu items that are expanded to show the childs as a dropdown and once just the child when the user is in the activeTrail. Would I try to alter menu_main with a hook, it would alter both because they're one block. I've just created a block in my module to load the menu_main and now I can alter the block to my liking without affecting the menu_main ^^
    – Kazuto
    Jun 13, 2018 at 9:12
  • That's important info. And drupal.org/project/menu_block just does what you need as it offers you menu configuration per block.
    – leymannx
    Jun 13, 2018 at 9:52

1 Answer 1

0

you can add new module twig tweak, after rendering blocks menu with Twig Tweak on template.

Your Answer

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

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