Zend_Navigation add class to active link
2010 September 6
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:
-
<?php
-
class My_Controller_Plugin_PrepareNavigation extends Zend_Controller_Plugin_Abstract
-
{
-
public function routeShutdown(Zend_Controller_Request_Abstract $request)
-
{
-
$viewRenderer = Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer');
-
$viewRenderer->initView();
-
$view = $viewRenderer->view;
-
-
$container = new Zend_Navigation(Zend_Registry::get('configuration')->navigation);
-
foreach ($container->getPages() as $page) {
-
$uri = $page->getHref();
-
if ($uri === $request->getRequestUri()) {
-
$page->setClass('active');
-
}
-
}
-
$view->navigation($container);
-
}
-
}
One Response
leave one →
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?