Symfony2 default locale in routing
If someone is interested in, I succeeded to put a prefix on my routing.yml
without using other bundles.
So now, thoses URLs work :
www.example.com/www.example.com//home/www.example.com/fr/home/www.example.com/en/home/
Edit your app/config/routing.yml
:
ex_example: resource: "@ExExampleBundle/Resources/config/routing.yml" prefix: /{_locale} requirements: _locale: |fr|en # put a pipe "|" first
Then, in you app/config/parameters.yml
, you have to set up a locale
parameters: locale: en
With this, people can access to your website without enter a specific locale.
You can define multiple patterns like this:
example_default: pattern: /example defaults: { _controller: ExampleBundle:Example:index, _locale: fr }example: pattern: /{_locale}/example defaults: { _controller: ExampleBundle:Example:index} requirements: _locale: fr|en
You should be able to achieve the same sort of thing with annotations:
/** * @Route("/example", defaults={"_locale"="fr"}) * @Route("/{_locale}/example", requirements={"_locale" = "fr|en"}) */
Hope that helps!
This is what I use for automatic locale detection and redirection, it works well and doesn't require lengthy routing annotations:
routing.yml
The locale
route handles the website's root and then every other controller action is prepended with the locale.
locale: path: / defaults: { _controller: AppCoreBundle:Core:locale }main: resource: "@AppCoreBundle/Controller" prefix: /{_locale} type: annotation requirements: _locale: en|fr
CoreController.php
This detects the user's language and redirects to the route of your choice. I use home as a default as that it the most common case.
public function localeAction($route = 'home', $parameters = array()){ $this->getRequest()->setLocale($this->getRequest()->getPreferredLanguage(array('en', 'fr'))); return $this->redirect($this->generateUrl($route, $parameters));}
Then, the route annotations can simply be:
/** * @Route("/", name="home") */public function indexAction(Request $request){ // Do stuff}
Twig
The localeAction can be used to allow the user to change the locale without navigating away from the current page:
<a href="{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale': targetLocale })) }}">{{ targetLanguage }}</a>
Clean & simple!