4

I want to define the page language via url on a Symfony2 installation. My routing works via annotation inside the controller.

routing.yml

_index:
    resource: "@MyMainBundle/Controller/SiteController.php"
    type:     annotation

siteController.php

/**
 * @Route( "/{_locale}/{site}", name="_site_site", defaults={"_locale" = "en"}, requirements={"site" = "about|cities|download|blog", "_locale" = "en|de|fr|es"} )
 */

This works quiet well, but waht I want, is that the following url call the same action.

http://example.com/download
http://example.com/en/download
http://example.com/de/download

Without the languge-parameter, the page should switch back to the default language, but this is something I can handle inside my action.

I found this Answer, but could not get it to work at all. Symfony2 default locale in routing

Community
  • 1
  • 1
madc
  • 1,674
  • 2
  • 26
  • 41

4 Answers4

10

Just add another @Route annotation that does not include the locale.

/**
 * @Route("/{_locale}/{site}/")
 * @Route("/{site}/")
 */
Kris Wallsmith
  • 8,945
  • 1
  • 37
  • 25
  • 3
    Thanks! I just had to add 'defaults={"_locale"="en"}', otherwise it leads to an error, if no locale is found in the url. – madc Jan 17 '12 at 15:31
  • you can add locale in routing.yml after type="annotation" requirements: _locale: en|fr – khaled_webdev Feb 28 '14 at 21:20
3

This also works within annotations.yaml

frontend_controllers:
    resource: ../../src/Controller/Frontend
    type: annotation
    prefix:
        - /
        - /{_locale}
    defaults:
        _locale: 'en'
1

Another simular solution for Symfony 5 that worked for me :

# config/routes/annotations.yaml
controllers:
    resource: '../../src/Controller/'
    type: annotation
    prefix:
        fr: ''
        en: '/en'

Symfony documentation : https://symfony.com/doc/current/routing.html#localized-routes-i18n

Adrien LAMOTTE
  • 548
  • 4
  • 8
0

Also if you have an api prefix you can use next config

controllers:
resource: ../../src/Controller/
type: annotation
prefix:
    - api
    - api/{_locale}
defaults:
        _locale: en