Symfony2 在路由中使用默认语言环境(一种语言的一个 URL) [英] Symfony2 Use default locale in routing (one URL for one language)

查看:26
本文介绍了Symfony2 在路由中使用默认语言环境(一种语言的一个 URL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用 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.

这篇关于Symfony2 在路由中使用默认语言环境(一种语言的一个 URL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆