Symfony2 - get the main request for the current route in the partial / subquery branch

In the partial part of Twig processed by a separate controller, I want to check if the current main route matches the compared route, so I can mark the list item as active.

How can i do this? Trying to get the current route in BarController, for example:

$route = $request->get('_route'); 

returns null .

Uri also not what I'm looking for, like calling the code below in bar twig:

 app.request.uri 

returns a route similar to: localhost/_fragment?path=path_to_bar_route

Full example

Main controller: FooController extends the controller {

  public function fooAction(){} } 

fooAction twig:

 ...some stuff... {{ render(controller('FooBundle:Bar:bar')) }} ...some stuff... 

Panel Controller:

 BarController extends Controller{ public function barAction(){} } 

barAction twig:

 <ul> <li class="{{ (item1route == currentroute) ? 'active' : ''}}"> Item 1 </li> <li class="{{ (item2route == currentroute) ? 'active' : ''}}"> Item 2 </li> <li class="{{ (item3route == currentroute) ? 'active' : ''}}"> Item 3 </li> </ul> 
+6
source share
3 answers

pabgaran should work. However, the original problem is probably due to request_stack .

http://symfony.com/blog/new-in-symfony-2-4-the-request-stack

Since you are in a subquery, you should get the top level ( master ) Request and get _route . Something like that:

 public function barAction(Request $request) { $stack = $this->get('request_stack'); $masterRequest = $stack->getMasterRequest(); $currentRoute = $masterRequest->get('_route'); ... return $this->render('Template', array('current_route' => $currentRoute ); } 

Do not run this, but it should work ...

+12
source

I think the best solution in your case went through the current main route in rendering:

 {{ render(controller('FooBundle:Bar:bar', {'current_route' : app.request.uri})) }} 

Then return it in response:

 public function barAction(Request $request) { ... return $this->render('Template', array('current_route' => $request->query->get('current_route')); } 

And in your template is compared with the received value.

Otherwise, it might be better to use include instead of rendering if you do not need additional logic for partial.

+2
source

in the branch, you can send the request object from the main controller to the sub-controller as a parameter:

 {{ render(controller('FooBundle:Bar:bar', {'request' : app.request})) }} 

in the subcontroller:

 BarController extends Controller{ public function barAction(Request $request){ // here you can use request object as regular $country = $request->attributes->get('route_country'); } } 
+1
source

Source: https://habr.com/ru/post/986965/


All Articles