drupaldrupal-7drupal-themingdrupal-navigation

Drupal 7 - Appending class names to a menu block <ul>


I've been stuck on how to manipulate in the template file what a menu block outputs in it's html. The regular < ul class="menu" > with li links is fine and I don't need to completely gut this html that drupal creates for all menus but I want to inject classes 'inline' and 'links' like the system main menu (usually) already has under it's ul element. I could print the menu directly in the theme skipping blocks altogether but it would be more helpful in the long run to learn injecting class names into the output of menu blocks that are generated.

So far from googling around I've only been able to find a module that can enter ID's and Class names on the individual li's but not the ul wrapping them and I've been unable to get any similar template file snippets I've come across to work.

There is a way to use a hook function to do this isn't there?


Solution

  • Why don't you add the classes you want via javascript?!

    Example:

    jQuery("#MY_MENU_WRAPPER ul.menu").addClass("inline");
    

    If that's the case, try the following code in your theme's template.php file

    function return_menu_markup($menu_name, $attributes)
    {
        $items = array();
        $menu_tree = menu_tree_all_data($menu_name);
        $menu_tree_output = menu_tree_output($menu_tree);
    
        foreach($menu_tree_output as $item_id => $item_data)
        {
            if(is_numeric($item_id) && is_array($item_data))
            {
                $items[] = l('<span>' . $item_data['#title'] . '</span>', $item_data['#href'], array(
                        'attributes'    => $item_data['#attributes'],
                        'html'      => TRUE,
                    )
                );
            }
        }
        return theme('item_list', array('items' => $items, 'type' => 'ul'));
    }
    

    Then anywhere in the template, simply do the following:

    $attributes = array();
    $attributes['id'] = "MY_MENU_ID";
    attributes['class'] = array('MY_CLASS_1', 'MY_CLASS_2', 'MY_CLASS_3');
    return_menu_markup("main-menu", $attributes);
    

    Hope you find what needed :)

    -Muhammad.