Symfony2 Use default locale in routing (one URL for one language)

大兔子大兔子 提交于 2019-11-29 12:48:49

问题


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.



来源:https://stackoverflow.com/questions/22086755/symfony2-use-default-locale-in-routing-one-url-for-one-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!