round image on layout top

Get active link for navigation in symfony

July 23, 2010 by Bebel divider image
symfony-navigation

Today I want to show you some quick tip for symfony.
You probably already had this problem or will run into it one day: You have a navigation and want to activate the current element with some special css class for a better user experience.

So did I with my current project – again. Because I don’t want to use project specific solutions all the time I finally decided to write a custom helper for this problem. It is really flexible and can be used for different methods to activate the desired css class.

Here the Code of the NavigationHelper.php which I’ve put in /lib/helper/.

/**
 * check if navigation element is active by checking for a request
 * parameter element and return css class
 * @param $menuPoint
 * @param String $type
 * @param String $cssClass
 * @return String
 */
function nav_active($menuPoint, $type = 'module', $cssClass = 'active') {

  $params = sfContext::getInstance()->getRequest()->getParameterHolder()->getAll();

  if(!is_array($menuPoint)) {
    $menuPoints[] = $menuPoint;
  }else {
    $menuPoints = $menuPoint;
  }

  foreach($menuPoints as $mp) {
    if (isset($params[$type]) && $mp == $params[$type]) {
      return ' class="'.$cssClass.'"';
    }
  }

  return '';

}

The code should be really straight forward and easy to understand. Here an example of the usage:

First, make sure you have included the helper. You can do that either by including the helper in every template you are using this method:

use_helper('Navigation');

Or by including it in the standard_helpers list in the settings.yml

standard_helpers:       [..., Navigation]

And finally, we build some neat navigation:

<ul id="nav">
  <li><a <?php echo nav_active('project_category') ?> href="<?php echo url_for('@project_category') ?>">Categories</a></li>
  <li><a <?php echo nav_active(array('project', 'project_content')) ?> href="<?php echo url_for('@project') ?>">Projects</a></li>
</ul>

The nice part of this helper is, that it can check the url for multiple modules / actions or whatsoever. You can either use a simple string to define only one module or action or an array of them.

Your navigation could now look like this:

I hope this code will help you take care of your navigation. If you have improvements to share, please feel free to add a comment to this post!


Share this post

Your email address will not be published. Required fields are marked *

Username*

Email*

Blog / Homepage?

Comment


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



bottom round image

footer blue big nice

footertop right
Style © 2010 by Bebel. | Running on wordpress