首页 文章

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

提问于
浏览
10

我目前正在开发一个使用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}

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

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

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

http://symfony.com/fr/doc/current/book/translation.html 显示法国的traduction

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 (以英文显示页面)

1 回答

  • 10

    安装JMSI18nBundle并应用策略 prefix_except_default .

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

    configuration:

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

    更多信息可以在包的documentation中找到 .

相关问题