4

Seems so elementary but how does one get the active state onto the <li> of a link when manually using the l() function?

<li><?php print l('Hapiness','my/hapiness/complete', array('attributes' => array(), 'html' => FALSE)); ?></li>

The above of course outputs the link in a list item with an active class on the link if the page is current, but how do I get that class onto the <li>?

1
  • You won't need the third arg for the l() function at all because html and attribute parameters' default values are same as what you have entered.
    – AKS
    Sep 17, 2012 at 8:01

4 Answers 4

7

You can't. The l() function is only responsible for rendering the HTML link, it has no concept of the tag it's being wrapped in (or indeed if it's even being wrapped in another tag at all).

The simple answer based on your question is to add it manually:

<li class="active"><?php print l('Hapiness','my/hapiness/complete', array('attributes' => array(), 'html' => FALSE)); ?></li>
1
  • 2
    Thanks for the response, I ended up using arg(3) as it was a controlled set of views filters so it ends up as: <li<?php print (arg(3))? '' : ' class="active"' ;?>><?php print l('All',...
    – Duncanmoo
    Jul 4, 2012 at 9:47
3

menu_get_item() returns the current active menu item. So you can decide on that, ej:

$classes = '';
$path = 'my/hapiness/complete';
$current = menu_get_item();
if ($current == $path) {
  $classes .= 'active';
}
print "<li class='$classes'>" . l(...) . "</li>";
1
  • Thanks @jonhattan menu_get_item() is a good solution for most pages, but in this particular case (not mentioned in the question) the last argument is a views contextual filter so 'my/hapiness/complete' and 'my/hapiness/incomplete' both give 'my/hapiness' as a path in menu_get_item().
    – Duncanmoo
    Jul 4, 2012 at 15:39
2
l('<link text>', '<link path>', array('attributes' => array('class' => array('class-a', 'class-b'))));
1
  • Yes this allocates a class to the <a href> tag but the question was about adding the active state to the <li> wrapping the link.
    – Duncanmoo
    Sep 18, 2012 at 6:42
-2
$output = '';

$submit_links = array();

$outp = array('0'=>10, '1'=>'20');

foreach ($outp as $key => $value) {
  // if you have dynamic links
  $submit_links[] = l(t('LINK TEXT HERE'), 'node/'. $value, array('attributes' => array('target'=>'_blank', 'class' => 'menu',), 'html' => TRUE));
}

$output = theme('item_list', array('items' => $submit_links));

return $output;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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