I wish to access the $route variable generated in my controller from an included file in my twig templates and after many attempts I am failing to do so.
I define the $route variable at the controller like this:
$route = $request->attributes->get('_route');
Then I send the variables to my twig template
return $this->render('destinations/index.html.twig', [
'route' => $route,
'locale' => $locale,
'langs' => $langs,
'menu' => $menu
]);
From base.html.twig I call navbar.html.twig
{{ include('shared/navbar.html.twig') }}
When I try to print {{ route }} from inside navbar.html.twig I get a symfony error saying that route variable does not exist.
Also, if I try {{ app.request.attributes.get('_route') }} from base.html.twig I get the route, but if I do so from shared/navbar.html.twig I get "null". Why is that happening?
My Answer:
>get('_route');
Then, in your Twig template, you can pass the $route variable to the included file like this:
twig
{% include 'your_included_file.twig' with {'route': route} %}
Now, in your included file, you can access the $route variable like any other variable:
twig
{{ route }}
This should allow you to access the $route variable in your included Twig file.
Rate this post
4 of 5 based on 1168 votesComments