Symfony2在路由中使用默认语言环境(一种语言的一个URL)

mlp*_*lpo 10 php routing locale translation symfony

我目前正在开发一个使用Symfony2的网站,我需要翻译它.使用Symfony2提供的工具非常简单.但是我遇到了一个问题:

我想要一种语言(即一个URL,一种语言)的特定URL(带前缀),但使用默认语言.具体来说:

假设默认语言是英语,那么

  • http://example.com/fr/hello 用法语显示页面
  • http://example.com/it/hello 用意大利语显示页面
  • http://example.com/en/hello重定向到http://example.com/hello(因为en是默认语言)
  • http://example.com/hello 当然显示英文页面(默认语言)

我天真地尝试像这样配置我的路由:

#routing.yml
_welcome:
    pattern:  /{_locale}/hello
    defaults: { _controller: AcmeDemoBundle:Welcome:hello, _locale: en}
Run Code Online (Sandbox Code Playgroud)

但这不起作用(http://example.com/en/hello只显示英文页面并http://example.com/hello返回404错误).

当然,每次创建两条路线是可能的,但这非常繁琐.所以我正在寻找一个干净的解决方案.

顺便说一下,我注意到我用URL查找的行为正是Symfony2官方文档所采用的行为:

http://symfony.com/fr/doc/current/book/translation.html 展示法国传统

http://symfony.com/it/doc/current/book/translation.html 显示意大利语traduction

http://symfony.com/en/doc/current/book/translation.html重定向到http://symfony.com/doc/current/book/translation.html(以英文显示页面)

Nic*_*ich 10

安装JMSI18nBundle并应用策略prefix_except_default.

捆绑包将负责为您创建路线.

组态:

jms_i18n_routing:
    default_locale: en
    locales: [de, en]
    strategy: prefix_except_default
Run Code Online (Sandbox Code Playgroud)

更多信息可以在软件包的文档中找到.

  • symfony 3有解决方案吗? (3认同)
  • 创建一个[`kernel.request`](http://symfony.com/doc/current/cookbook/service_container/event_listener.html)侦听器,执行重定向/剥离URL的`{_locale}'部分以防万一默认语言环境 - >解谜.我相信你会自己找出那个......如果你被卡住了......问一个新问题:) (2认同)