I want to use KnpMenu for a current project to handle my navigation tree logic. I have build a menu tree like this:
use Knp\Menu\Matcher\Matcher;
use Knp\Menu\MenuFactory;
use Knp\Menu\Renderer\ListRenderer;
$factory = new MenuFactory();
$menu = $factory->createItem('my_menu');
$menu->addChild('home', array('uri' => '/', 'label' => 'Home'))
->addChild('about', array('uri' => 'about', 'label' => 'About'));
$cat1 = $menu->addChild('category_1', array('uri' => 'category_1', 'label' => 'Category 1'));
$cat1_1 = $cat1->addChild('category_1_1', array('uri' => 'category_1_1', 'label' => 'Category 1.1'));
$cat1_1->addChild('category_1__1', array('uri' => 'category_1_1_1', 'label' => 'Category 1.1.1'));
$cat1_1->addChild('category_1_1_2', array('uri' => 'category_1_1_2', 'label' => 'Category 1.1.2'))->setCurrent(true);
$cat1->addChild('category_1_2', array('uri' => 'category_1_2', 'label' => 'Category 1.2'));
$renderer = new ListRenderer(new Matcher());
echo $renderer->render($menu);
I was wondering if it is possible to render a folded menu tree where only the currently active menu items are displayed. The other items should not be displayed. In the documentation I haven't found a way to accomplish this.
Does anyone have a solution?
Thank you
Do you mean that you only want to have the menu 'unfolded' if the parent is active?
If so, then yes, I had the same requirement, and there is a PR open for it here https://github.com/KnpLabs/KnpMenu/pull/85
Currently as it's not merged I am using my branch to replace the tagged KnpMenu in composer.
//composer.json excerpt
...
"repositories": [
{
"type": "vcs",
"url": "git@github.com:catchamonkey/KnpMenu"
}
],
require: {
...
"knplabs/knp-menu": "dev-display_children_if_ancestor_current as 2.0.0",
...
}
...
You then tag the top level item with this behaviour, so to make your category_1 only expand if a child is active (or it is active), you would do
$cat1->setDisplayChildrenIfAncestorCurrent(true);
And this is handled by the twig rendered change here https://github.com/KnpLabs/KnpMenu/pull/85/files#L2R74