Richard Knop
Richard Knop

Reputation: 83725

Zend_Navigation add class to active link

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);
}

Upvotes: 0

Views: 2900

Answers (2)

Frank Thoeny
Frank Thoeny

Reputation: 310

This is how to create a navigation() in a layout() with zend frameworks using Application. Well, at least one way of doing it. the CSS class is set on the

put this into the Bootstrap.php file:

protected function _initNavigation() 
{
     $this->bootstrap('layout');
     $layout = $this->getResource('layout');
     $view = $layout->getView();        
     include APPLICATION_PATH . '/layouts/scripts/menu.phtml';      
     $view->navigation($container);
}    

This allows you to create an array for a menu in the file menu.phtml, so that you can still maintain the active class on the current link. For some strange reason, if you use this you must include the controller property in the array to get the CSS active class on the current link.

put something like this into the /layouts/scripts/menu.phtml file:

$container = new Zend_Navigation(array(
array(
    'label' => 'HOME',
    'id' => 'tasks',
    'uri'=>'/',
    'controller' => 'Index'
),
array(
    'label' => 'Contact',
    'uri' => 'contact',
    'controller' => 'Contact'
), 

.... more code here ...        

put this into the layout.phtml file:

$options = array('ulClass' => 'menu');

Upvotes: 0

Richard Knop
Richard Knop

Reputation: 83725

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);
    }
}

Upvotes: 2

Related Questions