How can i create a link to the current in my template?
I want to create a language switcher which should link to the current page in varios languages, so all parameters should be the same exept for the locale.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I end up rolling my own function for this. I though at first it was included somewhere in
FrameworkBundlebut did not find anything about it. Here the steps I took.At first, I created a Twig extension function that would output the same route as the one the user is visiting currently (parameters and query string included). I left this step to you. You can look at this link from a good tutorial on Symfony2 for the description of how to create a Twig extension if you don’t know how already. I could help you with it if you need it.
Next step is to create the function itself that will switch the locale of the current route. This function will need the
RequestandRouterobjects as dependencies. In my personal case, I put this function in a dedicated service namedRoutingHelperservice. This service is then used by my Twig extension function. Here the service definition I added to the dependency container:And the constructor of my service:
The $locale parameter is new locale would like to switch to. Here the function:
Essentially, it does what others have put so far but it also handles parameters and query string. The method
filterPrivateKeyswill remove private attribute from the route attributes. Those attributes are the one starting with an underscore and should not be passed back to the route generator. Here its defintion:In the end, I’m able to this in my Twig view to create links to switch locales:
Edit:
Here my twig extension service definition:
And in the twig extension function I have this call:
$routingHelper = $this->container->get('acme.helper.routing');This should solve the scope widening exception happening because the twig extension is not in the request scope.
Update:
It is now possible with Symfony 2.1 to have a locale switcher in an easier way than before. Indeed, the 2.1 version of Symfony introduced a new parameter for routes that make it more easy to do a locale switcher. Here the code, all in twig
It is still a few lines of twig code, but could be included in a Twig block for easier reuse. Credits to stof, from the Symfony community, for the code above.
Hope this is what you are looking for.
Regards,
Matt