Knp Menu Bundle Current item Symfony 2

acid picture acid · Jul 23, 2012 · Viewed 13.1k times · Source

I have a question regarding rendering the KnpMenu Bundle for Symfony2. From I've read, there should be a "current" class at the matched route item. I've read the Knp documentation and they're saying something about RouteVoter but I can't make it working. Any ideas?

Builder code:

<?php
// src/Acme/DemoBundle/Menu/Builder.php
namespace Acme\DemoBundle\Menu;

use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;

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

        $menu->addChild('Home', array('route' => 'index'));
        $menu->addChild('About Me', array('route' => 'products'));

        return $menu;
    }
}

Answer

Aries VII picture Aries VII · Jun 4, 2013

It's 10 months on and I followed the solution outlined above, however I found it to be convoluted. I use the following method.

class Builder extends ContainerAware
{
    public function mainMenu(FactoryInterface $factory, array $options)
    {
        $menu = $factory->createItem('root');
        // Manually set the current URI.
        $menu->setCurrentUri($this->container->get('request')->getRequestUri());
        // ... 
    }
}

I've turned a blind eye to semantics, but what wrong with an approach like the above code sample? Please provide feedback as required.