ex3v ex3v - 5 months ago 42
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');


returns
null
.

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

app.request.uri


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


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:

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

Answer

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

http://symfony.com/blog/new-in-symfony-2-4-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...

Comments