Creating breadcrumbs in symfony 2.1 using knpmenu bundle

Mister Been picture Mister Been · Nov 13, 2012 · Viewed 7.1k times · Source

What's the best way to create breadcrumbs using knpmenu bundle in symfony 2.1.x ? Aside from using 3-rd party bundles.

UPDATE:

Hi, theunraveler, sorry for late answer. Now I've been following your example and I'm stuck at one moment. Here, code below throws an exception, that

Missing argument 2 for Acme\DemoBundle\Menu\MenuBuilder::getBreadCrumbs()    

{% set item = knp_menu_get('main') %}
{{ knp_menu_render(item) }}
{% block breadcrumbs %}
    {% set breadcrumbs = knp_menu_get('breadcrumbs', [], {'request':    app.request, 'menu': item }) %}
    {{ dump(breadcrumbs) }}
{% endblock %}

Why it doesn't accepts "item" variable?

Answer

b.b3rn4rd picture b.b3rn4rd · Mar 4, 2015

Since version 2.0, getBreadcrumbsArray has been moved to Knp\Menu\Util\MenuManipulator.

Possible workout to this solution is to create a twig extension:

<?php

namespace Kimwild\CommonBundle\Twig;
use Knp\Menu\Util\MenuManipulator;
use Knp\Menu\ItemInterface;

class MenuManipulatorExtension extends \Twig_Extension
{

    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('menu_manipulator', array($this, 'menuManipulator')),
        );
    }

    public function menuManipulator(ItemInterface $item)
    {
        $manipulator = new MenuManipulator();
        return $manipulator->getBreadcrumbsArray($item);
    }


    public function getName()
    {
        return 'menu_manipulator';
    }

}

Register twig extension:

kimwild_common.menu_manipulator_extension:
    class: Kimwild\CommonBundle\Twig\MenuManipulatorExtension
    public: false
    tags:
        - { name: twig.extension }

In breadcrumb.html.twig:

{% block root %}
    {%- for  link in menu_manipulator(item) %}
    /* whatever you want to do ... */
    {%- endfor %}
{% endblock %}