0

I am building a Bootstrap 3 sub theme where I want to display some information next to menu link in main menu. I tried to implement hook_menu_link_alter in template.php file in following way

function mytheme_menu_link_alter(&$item){
if($item['title'] == 'Messages'){
$item['title']= $item['title'].'<span class="badge">X</span>';
}
}

but it does not work. The same stuff with link_title. Whta should be fixed in code to make it work?

1 Answer 1

1

you can override the output of theme_menu_link() to produce what you want:

function THEME_menu_link(&$variables)
{
    $element = $variables['element'];
    $sub_menu = '';

    $element['#attributes']['class'][] = 'menu-' . $element['#original_link']['mlid'];

    if ($element['#below'])
    {
        $sub_menu = drupal_render($element['#below']);
    }
    $output = l($element['#title'], $element['#href'], $element['#localized_options']);


    if($variables['element']['#title'] == 'Messages')
    {
        // to just add the text
        $output .= '<span class="badge">X</span>';

        // to include it as a link
        $output .= l('X', $element['#href'], array('attributes' => array('class' => 'badge')));
    }

    return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}
4
  • Thanks for idea. I've modified to display <span> in a link tag $element['#title'] .= '<span class="badge">X</span>';. But instead < > " symbols were converted to html entities. Is there any way to display them as part of html tag? Commented Jun 15, 2015 at 15:34
  • Im not sure I understand that last comment - you want to display <span class="badge">X</span> as part of the text, as part of the actual href link, or you want to display the X within the <span> as part of the href?
    – Geoff
    Commented Jun 15, 2015 at 15:40
  • Link is displayed like <a href="#">Messages&lt;span class=&quot;badge&quot;&gt;X&lt;/span&gt;</a>. Is there any way to fix that? Commented Jun 15, 2015 at 15:42
  • Drupal sanitizes a link - this is a security feature to protect against certain attacks, so I don't think you can incorporate it into a single link - I modified the answer to include an option for creating a separate <a> with the class 'badge' that sits beside the original and directs to the same location. Should be seemless to the end user
    – Geoff
    Commented Jun 15, 2015 at 15:49

Your Answer

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

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