Drupal: Using Of Primary/Secondary Links to Build Two-Level Separate Menu
In this article we will learn how to:
- Create two-level menu.
- Place first-level menu items are at the top, second-level menu items (submenus) appear at the left side.
- Parent menu item stays active when a user navigates by its subelements.
Solution:
Below there are a few steps which will help you to create two-level menu (choosing parent items first, then making menu item primary and/or secondary in the menu settings and specifying allocation of the menus in the form of ‘links’ in page.tpl.php):
- Go to: Admin → Construction → Menu
- Create menu (you can add the required items right in primary links – the menu is already created by default). To make a multi-level menu, choose a parent for the items. Don’t need to create 2 separate menues.
- Open Settings tab and choose:
Menu with primary links: your menu (Primary links)
Menu with secondary links: your menu (Secondary links) - Insert the following code into page.tpl.php:
For primary links:<?php if (isset($primary_links)) { ?><?php print theme(‘links’, $primary_links) ?><?php } ?>
For secondary_links:
<?php if (isset($secondary_links)) { ?><?php print theme(‘links’, $secondary_links) ?><?php } ?>
This method could be applied for two-level menu only.
To create a parent link with class=”active”, use TemplatePHP snippet from this page. Insert the following code to template.php (without closing ?>
).
<?php
function phptemplate_links($links, $attributes = array()) {
if (!count($links)) {
return ”;
}
$level_tmp = explode(‘-‘, key($links));
$level = $level_tmp[0];
$output = “<ul class=\”links-$level “.$attributes[‘class’]. “\”>\n”;
foreach ($links as $index => $link) {
$output .= ‘<li';
if (stristr($index, ‘active’)) {
$output .= ‘ class=”active”‘;
}// frontpage AND current-link in menu is <front>
elseif((drupal_is_front_page()) && ($link[‘href’]=='<front>’)){
$link[‘attributes’][‘class’] = ‘active';//add class active to <li
$output .= ‘ class=”active”‘;//add class active to <a
}
$output .= “>”. l($link[‘title’], $link[‘href’], $link[‘attributes’], $link[‘query’], $link[‘fragment’]) .”</li>\n”;
}
$output .= ‘</ul>';
return $output;
}
?>
Good luck!