1
votes

I render my header.twig from the base.twig file via the render function. So in my base.twig there is the following code to trigger header controller:

{{ render(controller('MyBundle:Global:header')) }}

That controller renders the header.twig. In this twig file there the the following code link for changing the language:

<a href="{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale' : app.request.locale })) }}"><img src="{{ asset('flags/'~app.request.locale~'.png', 'img') }}" /></a>

The objects form app.request.get('_route') and app.request.get('_route_params') both return null.

app.request.get('_route')

If I run the same code link directly in the base.twig the request returns the correct objects. Looks like because the header.twig has it own controller the request are not working. Is it possible to request the route and parametsr of the active url in a other way?

2
Use app.request.get('_route_params', {}) so that if there are no _route_params it will default to an emty object. - qooplmao
That helps in removing the error only I need the values as these should be available around the application. These are the standaard route url and the parameters in the url. - Tom

2 Answers

2
votes

Adding to @Gustek's answer because I missed the actual issue in the first case.

You are actually rendering a sub request so the _route and _route_params are from the sub request rather than the main request. As you are using a controller the cleanest approach would be to get the parameters from the master request and pass those in as parameters in the controller call. You could pass them in through the render call (as @Gustek has answered) but that would mean you would mean to do it with every call, or you could pass the request stack into the twig session but that would be unnecessary extra work.

public function headerAction(Request $request)
{
    $masterRequest = $this->container->get('request_stack')->getMasterRequest();

    //...

    return $this->render('MyBundle:Global:header.html.twig', [
        //...
        '_route'        => $masterRequest->attributes->get('_route'),
        '_route_params' => $masterRequest->attributes->get('_route_params'),
    ]);
}
2
votes

controller method takes 2 optional arguments. http://symfony.com/doc/current/reference/twig_reference.html#controller

Not 100% sure about it but maybe this will work:

{{ render(controller('MyBundle:Global:header',
  {
    '_route': app.request.get('_route'),
    '_route_params': app.request.get('_route_params')
  }
)) }}