Symfony2 Use default locale in routing (one URL fo

2019-02-06 15:33发布

问题:

I am currently developing a website with Symfony2 and I need to translate it. With tools provided by Symfony2 it’s very easy. But I encounter a problem:

I would like to have specific URL (with prefix) to a language (ie, one URL, a single language), but with a default language. Concretely:

Assume that the default language is English, so

  • http://example.com/fr/hello display the page in French
  • http://example.com/it/hello display the page in Italian
  • http://example.com/en/hello redirect to http://example.com/hello (because en is the default language)
  • http://example.com/hello display of course the page in English (default language)

I naively try to configure my routing like this:

#routing.yml
_welcome:
    pattern:  /{_locale}/hello
    defaults: { _controller: AcmeDemoBundle:Welcome:hello, _locale: en}

But that’s don’t work (http://example.com/en/hello just display the page in English and http://example.com/hello return 404 error).

It’s possible, of course, to create two routes each time, but it is very tedious. So I’m looking for a clean solution.

Incidentally, I noticed that the behavior I was looking for with URL was exactly the one adopted by the official documentation of Symfony2:

http://symfony.com/fr/doc/current/book/translation.html display French traduction

http://symfony.com/it/doc/current/book/translation.html display Italian traduction

http://symfony.com/en/doc/current/book/translation.html redirect to http://symfony.com/doc/current/book/translation.html (which display the page in English)

回答1:

Install JMSI18nBundle and apply the strategy prefix_except_default.

The bundle will take care of creating the routes for you.

configuration:

jms_i18n_routing:
    default_locale: en
    locales: [de, en]
    strategy: prefix_except_default

Further information can be found in the bundle's documentation.