简体   繁体   中英

KnpMenuBundle - how can i set an icon class to each elements of menu?

I want to my view code looks like this:

<li>
    <a href="path/to/action">
            <i class="icon-class"></i>
            <span class="title">Title</span>
    </a>
</li>

I create menu elements by Menu Builder:

class Builder extends ContainerAware
{
    public function adminMenu(FactoryInterface $factory, array $options)
    {
        $menu = $factory->createItem('root');

        $menu->addChild('Dashboard', array(
            'route' => 'admin_dashboard',
        ));

        return $menu;
    }
}

I have overwritten view with following code (knp_menu.html.twig):

{% block linkElement %}
    {% import _self as knp_menu %}
    <a href="{{ item.uri }}"{{ knp_menu.attributes(item.linkAttributes) }}>
        <i class="icon-class"></i>
        <span class="title">{{ block('label') }}</span>
    </a>
{% endblock %}

How can i pass a value of icon class name to <i> element in method adminMenu(), in Builder class? What is the most simple way to do it?

You can add any attribute you want with

$menu->addChild('Dashboard', array(
    'route' => 'admin_dashboard',
))->setAttribute('icon', 'icon-class');

then

{{ item.attribute('icon') }}

I'd suggest the use of extras instead of attributes , because attributes is used to render the li element's attributes.

$menu->addChild('Dashboard', array(
    'uri' => '#',
))->setAttribute('icon', 'icon-class');

and

{{ item.attribute('icon') }}

will probably be rendered as:

<li icon="icon-class"><a href="#"><i class="fa fa-icon-class" aria-hidden="true"></i> Dashboard</a></li>

Whereas:

$menu->addChild('Dashboard', array(
    'uri' => '#',
))->setExtra('icon', 'icon-class');

and

{{ item.extra('icon') }}

Will probably just be rendered as:

<li><a href="#"><i class="fa fa-icon-class" aria-hidden="true"></i> Dashboard</a></li>

Also see this answer: https://stackoverflow.com/a/19095287/2106834 .

Simply:

$menu->addChild('Home', ['route' => 'home_page'])
        ->setAttribute('icon', 'fa fa-home');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM