Skip to content

Zend_Navigation add class to active link

2010 September 6
by Richard Knop

It is often useful to highlight an active navigation menu link so users are clear about where they are. It is usually done by adding a class (for instance: “active”) to a link which points to a current request URI. When using Zend_Navigation it is a bit more complicated. I am using a controller plugin to add the class to the active link during the routeShutdown event:

  1. <?php
  2. class My_Controller_Plugin_PrepareNavigation extends Zend_Controller_Plugin_Abstract
  3. {
  4.     public function routeShutdown(Zend_Controller_Request_Abstract $request)
  5.     {
  6.         $viewRenderer = Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer');
  7.         $viewRenderer->initView();
  8.         $view = $viewRenderer->view;
  9.        
  10.         $container = new Zend_Navigation(Zend_Registry::get('configuration')->navigation);
  11.         foreach ($container->getPages() as $page) {
  12.             $uri = $page->getHref();
  13.             if ($uri === $request->getRequestUri()) {
  14.                 $page->setClass('active');
  15.             }
  16.         }
  17.         $view->navigation($container);
  18.     }
  19. }
One Response leave one →
  1. Pablo permalink
    February 3, 2012

    Great solution!!! It worked great! Just needs to register the plugin, I did it in the Bootstrap file within the __initRoutes() method.

    $autoloader = Zend_Loader_Autoloader::getInstance();
    $autoloader->registerNamespace(‘Navigation_’);
    $autoloader->suppressNotFoundWarnings(true);
    Zend_Controller_Front::getInstance()->registerPlugin(new Navigation_Controller_Plugin_PrepareNavigation());

    Do you think my register method is clean enough?

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS