views:

63

answers:

1

How can I add a class to the active navigation link? If a link points to URI /index/index and the request URI is also /index/index, I would like the link to have class, for example:

<li class="active">
    <a href="/index/index">Index</a>
</li>

This is how I am initializing navigation in the bootstrap:

protected function _initNavigation()
{
$navigation = new Zend_Navigation($this->getOption('navigation'));
$this->view->navigation($navigation);
}
A: 

Ok,

I have solved this by writing a controller plugin:

<?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);
    }
}
Richard Knop
The optimal solution would be create your own partial to render the menu and there handle the conditions. The above approach needs to walk all the elements twice (once in controller, second during the rendering).
takeshin