Snippets

Create an account or login to be able to add, comment and rate snippets.

Navigation

create styled navigation for current view

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.

by scott meves on 2006-11-02, tagged css  helper  navigation 

Comments on this snippet

gravatar icon
#1 Nicolas CHARLOT on 2006-11-06 at 07:49

It is a usefull tool.

I see quickly 3 problems I've already had :

  1. 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.

  2. 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 ;-)

  1. It could be better if the current state should be applied even if the url is not strictly equal. For instance when there are parameters : www.site.com/app/module/action, www.site.com/app/module/action?param1=value1 or for all actions of a same module For this trick, we can do : if ($route == substr ($current_route, 0, strlen ($route))
gravatar icon
#2 Pierre Minnieur on 2006-11-07 at 05:23

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).

You need to create an account or log in to post a comment or rate this snippet.