ZF2 custom attributes in navigation

zend-framework2

Solution

The Page classes have some dedicated setters for common attributes (`setLabel`, `setId`, `setUri` etc), If a setter not exists `__set` will be called. See the manual for more information about this and also about extending the `AbstractPage` class.

array(
    'label' => 'Page 1',
    'id' => 'home-link',
    'uri' => '/',
    'data-test' => 'blahblah'
),

Now you can do `$page->get('data_test')` and it will return blahblah.

Your second question is about altering the rendering of the menu (adding a attribute to the `li`. ZF2 is using the menu view helper to render a navigation menu. All the navigation view helpers have an option to use your own partial view for rendering using `setPartial()`.

In your viewscript:

$partial = array('menu.phtml', 'default');
$this->navigation()->menu()->setPartial($partial);
echo $this->navigation()->menu()->render();

In your partial view `menu.phtml` do something like this:

<ul>
<?php foreach ($this->container as $page): ?>
    <li data-test="<?=$page->get('data_test')?>"><?=$this->navigation()->menu()->htmlify($page)?></li>
<?php endforeach; ?>
<ul>

This will only render the highest level of the menu. If you have deeper/nested structure your custom view script will end up far more complex.

Hope this helps.

Problem

How would I add custom attributes into Zend Framework 2 navigation? I know I can add id or class -> but that's about it.... 1) How would I add `data-test='blahblah'` attribute for example? 2) Can I add attribute to `li` elements that contain actual links? ``` $container = new Zend\Navigation\Navigation(array( array( 'label' => 'Page 1', 'id' => 'home-link', 'uri' => '/', ), array( 'label' => 'Zend', 'uri' => 'http://www.zend-project.com/', 'order' => 100, ), ); ``` Edit: @Bram Gerritsen: Thanks for your answer. Yes - I can add `'data-test' => 'blahblah'` and retrieve it as `$page->get('data-test')` - but this still doesn't append it as an attribute into `<a></a>`.... Would I ahve to override htmlify to to that?

Original source