Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

twig

symfony

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>
like image 228
ex3v Avatar asked May 11 '15 11:05

ex3v


3 Answers

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

like image 87
Jovan Perovic Avatar answered Nov 04 '22 02:11

Jovan Perovic


I think that the best solution in your case is past the current main route in the render:

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

Next, return it in the response:

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

And in your template compares with the received value.

Otherwise, maybe is better to use a include instead a render, if you don't need extra logic for the partial.

like image 30
pabgaran Avatar answered Nov 04 '22 00:11

pabgaran


in twig you can send request object from main controller to sub-controller as parameter:

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

in sub-controller:

BarController extends Controller{

    public function barAction(Request $request){
// here you can use request object as regular
$country = $request->attributes->get('route_country');
}
}
like image 39
Kyrgyz Jigit Avatar answered Nov 04 '22 00:11

Kyrgyz Jigit