Drupal 7:以编程方式获得带有子菜单的主菜单


Drupal 7: programmatically get main menu with sub-menus

我想显示我的主菜单链接与子菜单链接具有单独的类和id。

这适用于第一级链接,但不幸的是不显示第二级链接,因为$main_menu值不包含它们:

                <?php print theme('links', array(
                    'links' => $main_menu,
                    'attributes' => array(
                        'id' => 'mobile-menu-links',
                        'class' => array('links', 'clearfix'),
                    ),
                )); ?>

任何想法?

您可以获得带有子菜单的主菜单,并像这样操作它:

    $main_menu_tree = menu_tree('main-menu');
    foreach ($main_menu_tree as $key => &$main_menu_item) {
        if (is_numeric($key)) {
            $main_menu_item['#below']['#theme_wrappers'][0] = 'some_other_theme_wrapper';
        }
    }
    print drupal_render($main_menu_tree);

这里,默认的主题包装器(menu_tree__main_menu)被some_other_theme_wrapper取代,这需要实现。

你可以在drupal stackexchange上找到许多讨论这个问题的帖子。这里只有一个:

https://drupal.stackexchange.com/questions/35066/i-want-to-customze-menu-tree-output

你也可以像这样分别渲染主菜单和子菜单:

        <div class="menu"> 
            <?php print theme('links__system_main_menu', array(
              'links' => $main_menu,
              'attributes' => array(
                'id' => 'main-menu-links',
              ),
              'heading' => array(
                'text' => t('Main menu'),
                'level' => 'h2',
                'class' => array('element-invisible'),
              ),
            )); ?>          
        </div>
        <?php endif;?>
        <?php if ($secondary_menu): ?>
        <div class="submenu">
            <?php print theme('links__system_secondary_menu', array(
              'links' => $secondary_menu,
              'attributes' => array(
                'id' => 'secondary-menu-links',
              ),
              'heading' => array(
                'text' => t('Sub menu'),
                'level' => 'h2',
                'class' => array('element-invisible'),
              ),
            ))
        </div>