KnpMenuBundle - send Options and use them in Twig

给你一囗甜甜゛ 提交于 2019-12-02 04:17:28

问题


I wrote the last days on my nav-bar-menu whit KnpMenuBundle. But I think of give it up. I want simply to give the Template a few parameters on the way and then react on it. I go crazy. Is it possible. I tried this:

$menu->addChild('Registration', array('route' => 'fos_user_registration_register',
                                      'icon'  => array('glyphicon' => 'briefcase')));

And then I wanna pick this in Twig-Template:

{% if icon['glyphicon'] is defined %}
    <span class="glyphicon glyphicon-{{icon['glyphicon']}} "></span>
{% endif %}

I tried a lot, but nothing works. It must be so simple. I can´t believe, that this should not be possible.


回答1:


Here is how i did it

The Menu class:

$menu->addChild('Home', array(
    'route' => 'home',
    'extras' => array('icon' => 'home')
));

My menu call in the template, i ask for a specific twig template

{{ knp_menu_render('MyBundle:Menu:primaryNav', {'template': 'MyBundle:Menu:primaryNav.html.twig'}) }}

In the twig template, i copy/paste the knpmenubundle template and edit some blocks. you may be able to do this with 'extends' and template's inheritance stuffs as well (probably a better idea).

Example of edited block for icon :

{% block spanElement %}
<a href="#" class="dropdown-toggle">
    {% if item.extras.icon is defined %}<i class="icon-{{ item.extras.icon }}"></i>{% endif %}
    <span class="menu-text"> {{ block('label') }}</span>
    <b class="arrow icon-angle-down"></b>
</a>
{% endblock %}

What you needed was probably this "extras" field in the menu class :)




回答2:


I don't know if this can still help but there's a much easier way to use font awesome with knp menu. There's an option where you can give a class to your link. You just need to create a child without a label an add setLinkAttribute. Ex:

$menu->addChild('', array('route' => 'backend_index'))->setLinkAttribute('class', 'fa fa-home');

This will create an "a" tag with the class fa fa-home. Even if font awesome documentation says the icons are designed for inline elements, it will work with "a" tag. You can then use some css to improve the design. In my case, I just changed font-size and line-height.



来源:https://stackoverflow.com/questions/19032623/knpmenubundle-send-options-and-use-them-in-twig

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!