URL中的i18n语言环境

我想将我的应用程序的所有url与locale一起使用,例如:

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

如果不在我的所有链接中传递区域设置,我怎么能这样做?

使用:path_prefix选项:

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

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

 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] ,它会自动添加它。 所以:

 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'生成本地化版本的链接:

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

您还可以使用上面的示例来更改当前区域设置。

我不确定url helper的名称是什么,所以只需键入rake routes即可找到它。

用作导轨指南:

 # config/routes.rb scope "/:locale" do resources :books end 

设置区域设置:

 before_filter :set_current_locale private def set_current_locale I18n.locale = params[:locale] end