ex3v ex3v - 1 year ago 171
PHP Question

Symfony2 - get main request's current route in twig partial/subrequest

In Twig partial rendered by separate controller, I want to check if current main route equals to compared route, so I can mark list item as active.

How can I do that? Trying to get current route in BarController like:

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


is also not what I'm looking for, as calling below code in
's twig:


returns route similar to:

Full example

Main Controller:
FooController extends Controller{

public function fooAction(){}

fooAction twig:

...some stuff...

{{ render(controller('FooBundle:Bar:bar')) }}

...some stuff...

Bar controller:

BarController extends Controller{

public function barAction(){}

barAction twig:

<li class="{{ (item1route == currentroute) ? 'active' : ''}}">
Item 1
<li class="{{ (item2route == currentroute) ? 'active' : ''}}">
Item 2
<li class="{{ (item3route == currentroute) ? 'active' : ''}}">
Item 3

Answer Source

pabgaran's solution should work. However, the original problem occurs probably because of the request_stack.


Since you are in a subrequest, you should be able to get top-level (master) Request and get _route. Something like this:

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 );

Haven't run this but it should work...