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

2022-01-02 00:00:00 translation locale routing php symfony

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

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:

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

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 显示法语页面
  • http://example.com/it/hello 显示意大利语页面
  • http://example.com/en/hello 重定向到 http://example.com/hello(因为 en 是默认语言)
  • http://example.com/hello 当然页面显示为英文(默认语言)
  • 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}

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

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.

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

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 显示法语翻译

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

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

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)

推荐答案

安装 JMSI18nBundle 并应用策略prefix_except_default.

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

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

配置:

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

可以在捆绑包的文档中找到更多信息.

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

相关文章