Styling a Zend Framework 2 Navigation Menu to Work with Bootstrap

Written by James Mansson on September 1, 2014 Categories: Bootstrap, Zend Framework 2

The Zend\Navigation component in Zend Framework 2 is integrated with the Menu view helper to allow a navigation object to be easily converted into HTML. This is mostly compatible with Bootstrap in terms of the HTML generated, but we need to specify the class of the ul element in order for it to be rendered correctly.

Let us assume that we have defined the navigation in our config/autload/global.php file along the following lines:

return array(
    'navigation' => array(
        'default' => array(
            array(
                'label' => 'Home',
                'route' => 'home',
            ),
        ),
    ),
    'service_manager' => array(
        'factories' => array(
            'navigation' => 'Zend\Navigation\Service\DefaultNavigationFactory',
        ),
    ),
);

Obviously we will have specified more elements than just “Home”, but the precise details will be application-specific.

In our layout, we may decide to place the navigation inside a Bootstrap navbar. The view helper will render the navigation as an unsigned list, with the list item representing the active page having its class set to active; this is all correct and does not need to change. However, we will need to set the class of the ul element. We can do this as part of the process of rendering the unsigned list as follows:

echo $this->navigation('navigation')
	->menu()
	->renderMenu(null, array(
		'ulClass' => 'nav navbar-nav'
	)
);

This naturally needs to be placed at the appropriate point within the structure of div elements that represent the Bootstrap navbar.

1 Comment on Styling a Zend Framework 2 Navigation Menu to Work with Bootstrap

1 Comment

Leave a Reply

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