URL 中的 i18n 语言环境 [英] i18n locale in the URL

查看:53
本文介绍了URL 中的 i18n 语言环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要我的应用程序的所有 url 和语言环境,例如:

I'd like to have all the url of my application with the locale, ex :

http://domain.com
http://domain.com/user/new

变成:

http://domain.com/en
http://domain.com/fr
http://domain.com/en/user/new
http://domain.com/fr/user/new

如果不在我的所有链接中传递语言环境,我怎么能做到这一点?

How could I do that without passing the locale in all my links ?

推荐答案

在路由中使用 :path_prefix 选项:

Use :path_prefix option in your routes:

map.namespace :my_locale, :path_prefix => "/:locale" do |localized|
  localized.resources :users
  localized.root :controller => 'your_controller', :action => 'your_action'
  # other routes
end

在您的应用程序控制器中添加:

In your application controller add:

before_filter :set_current_locale

private
def set_current_locale
  current_locale = 'en' # default one
  current_locale = params[:locale] if params[:locale]  # or add here some checking 

  I18n.locale = current_locale # if it doesn't work, add .to_sym    
end

要创建链接,请使用标准的 url 助手.如果你设置了 params[:locale] ,它会自动添加它.所以:

To create links use standard url helpers. If you have params[:locale] set, it will add it automaticaly. So:

photos_path  # /en/photos - if you are in en locale
photo_path(@photo) # /fr/photos/3 - if you are in fr locale

现在,如果您在任何没有区域设置的路径中:www.mysite.com",那么您可以通过添加 :locale => 来生成本地化版本的链接.'en':

Now, if you are in any path that is without locale: "www.mysite.com", then you can generate links to localized version with adding :locale => 'en':

users_path(:locale => 'en') # /en/users

您也可以使用上面的示例更改当前语言环境.

You can also use above example to change current locale.

我不确定 url 助手的名称是什么,所以只需输入 rake routes 即可找到它.

I'm not sure what would be names of url helpers, so just type rake routes to find it.

这篇关于URL 中的 i18n 语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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