10

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)

mlpo
  • 410
  • 4
  • 13

1 Answers1

10

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.

Nicolai Fröhlich
  • 51,330
  • 11
  • 126
  • 130
  • This solution responds only partially to my problem, `http://example.com/hello` display well the page in English, but `http://example.com/en/hello`should redirect me to the same page without prefix but return a 404 error… – mlpo Feb 28 '14 at 18:04
  • 2
    create a [`kernel.request`](http://symfony.com/doc/current/cookbook/service_container/event_listener.html) listener that performs the redirect/ strips away the `{_locale}` part of the url in case of the default locale -> puzzle solved. I'm sure you'll figure out that one on your own ... and if you're stuck ... ask a new question :) – Nicolai Fröhlich Feb 28 '14 at 19:24
  • 3
    is there a solution to this for symfony 3? – Joseph Astrahan Jan 11 '16 at 00:52