knplabs/KnpMenuBundle — Issue #84: How can I get current selected menu item from twig template?
Author: zhil
Created: 2011-11-15 16:57:34+00:00
State: open

I include knp menu in template with code like

{{ knp_menu_render('Bundle:Builder:mainMenu',{ 'currentClass': 'active','template': 'Bundle:Menu:main.html.twig' }) }}

I have 1 level menu and a lot of the pages on site, most of them are attached to some "Big" section on site within menu builder with code like

switch($this->container->get('request')->attributes->get('_route')) {
case "route1":
case "route2":
case "route3":
$menu['mainmenuMedia']->setCurrent(true);
break;
case "route4":
$menu['mainmenuNews']->setCurrent(true);
break;

I want to customize main layout based on selected route.

My question is - how should I do it, so I will not need to duplicate top menu selection code. I see a couple solution
1) render {{ knp_menu_render('Bundle:Builder:mainMenu',{ 'currentClass': 'active','template': 'Bundle:Menu:another_template.html.twig' }) }} and put needed customizations in another_template. Right now I need to customize only logo, so it may work as a solution, but if I will need to add more customization - it would create too much load on server - build menu and render it each time.
2) move section selection code from menu builder to new service, which will return current top section selected based on route, create global variable in twig. It seems to be the most "right" way.
3) use some knp_menu feature, which I dont know :)

Thanks for answers if any ;)