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

前端 未结 3 732
名媛妹妹
名媛妹妹 2020-12-31 18:46

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 tha

相关标签:
3条回答
  • 2020-12-31 19:10

    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.

    0 讨论(0)
  • 2020-12-31 19:15

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

    0 讨论(0)
  • 2020-12-31 19:17

    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');
    }
    }
    
    0 讨论(0)
提交回复
热议问题