![]() |
|
Snippets |
|
Often times in my navigation I want to change the style of the "current" tab, link, menu item, etc. to reflect that the user is in fact on that page. In order to do this I created a super simple helper called link_to_styled. I added this code to app/lib/helper/StyleHelper.php:
function link_to_styled($text, $route = '', $options = '', $class_name = 'current') { $current_route = sfRouting::getInstance()->getCurrentInternalUri(); if($route == $current_route) { if(is_array($options)) { $options['class'] = $class_name; } else { $options .= ' class='.$class_name; } } return link_to($text, $route, $options); }
and then in my global navigation template I do something like this:
<?php use_helper('Style') ?> <ul id="navlist"> <li><?php echo link_to_styled('My Friends', 'friends/list') ?></li> <li><?php echo link_to_styled('My Clubs', 'clubs/list') ?></li> <li><?php echo link_to_styled('My Events', 'events/list')?></li> </ul>
The helper will automatically add a class='current' to the link tag. This function could be made more robust, but for a quick and simple solution it seems to do the trick.
Comments on this snippet
It is a usefull tool.
I see quickly 3 problems I've already had :
The "current" state is often applied to li (it's no more a link since we are on it). I don't see simple issue for that think.
It's possible to have more that one class if(is_array($options)) { $options['class'] .= (empty($options['class']) ? '' : ' ') . $class_name; } else { preg_match('/class=/', $options) ? preg_replace('/class="/', ('class="' . $class_name . ' '), $options) : $options .= ' class='.$class_name; }
The syntax has to be verified ;-)
I think you want to have a navigation where the "active" module is having a class name which lets you style that tab as "active", am I right? Then I think you should build a navigation helper which will create a list automatically based on a YAML array and decideds which element has to be set active (I've done that already with AJAX and it's fine for me).