开发者

i18n locale in the URL

开发者 https://www.devze.com 2022-12-20 06:01 出处:网络
I\'d like to have all the url of my application with the locale, ex : http://domain.com http://domain.com/user/new

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

http://domain.com

http://domain.com/user/new

to become :

http://domain.com/en

http://domain.com/fr

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

http://domain.com/fr/us开发者_如何学运维er/new

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


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

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

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.

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


Use as in rails guide:

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

Set locale:

before_filter :set_current_locale

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

精彩评论

暂无评论...
验证码 换一张
取 消