Search code examples
phphtmldrupaldrupal-7drupal-theming

How do I modify output markup for system secondary menu in Drupal 7?


I want to modify the structure of the secondary menu in Drupal 7 that appears when you are logged in. The secondary navigation shows 'My Account' and 'Log Out' links. By default, this renders as:

<h2 class="element-invisible">Secondary Menu</h2>
<ul id="secondary-menu-links" class="links inline clearfix">
    <li class="menu-2 first">
        <a href="/user">My account</a>
    </li>
    <li class="menu-15 last">
        <a href="/user/logout">Log out</a>
    </li>
</ul>

The code in my theme that is generating this menu is:

<?php print theme('links__system_secondary_menu', array(
    'links'         => $secondary_menu,
    'attributes'    => array(
        'id'        => 'secondary-menu-links',
        'class'     => array('links', 'inline', 'clearfix'),
    ),
    'heading'       => array(
        'text'      => t('Secondary Menu'),
        'level'     => 'h2',
        'class'     => array('element-invisible'),
    ),
)); ?>

How can I get the following markup outputted instead of what was listed above?

<li class="secmenusep"><span>|</span></li>
<li class="menu-2 secnav_account">
    <a href="/user">My account</a>
</li>
<li class="secmenusep"><span>|</span></li>
<li class="menu-15 secnav_logout">
    <a href="/user/logout">Log out</a>
</li>

I want the h2 removed, as well as the ul, and add two additional li tags with pipes for separators, and add a unique class to each.

Your help is very much appreciated.


Solution

  • You can achieve this custom HTML for your secondary menu by defining your proper theme for links. Because links__system_secondary_menu is a theme hook pattern under the form of [base hook]__[context], you can easily implement a theme definition for this secondary menu within your theme by using YOURTHEME_links__system_secondary_menu.

    Inside the template.php of your theme, you can put this code which does exactly what you are asking for:

    function YOURTHEME_links__system_secondary_menu(&$variables)
    {
        $output = '';
        $extra_classes = array(
            'user' => 'secnav_account',
            'user/logout' => 'secnav_logout',
        );
    
        foreach ($variables['links'] as $item => $link) {
            $classes = array($item);
    
            if (isset($extra_classes[$link['href']])) {
                $classes[] = $extra_classes[$link['href']];
            }
    
            $output .= '<li class="secmenusep"><span>|</span></li>';
            $output .= sprintf(
                '<li class="%s">%s</li>', implode(' ', $classes), l($link['title'], $link['href']));
        }
    
        return $output;
    }