Mike
Mike

Reputation: 5193

i18n locale in the URL

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/user/new

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

Upvotes: 2

Views: 4886

Answers (2)

Jiemurat
Jiemurat

Reputation: 1629

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

Upvotes: 1

klew
klew

Reputation: 14967

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.

Upvotes: 2

Related Questions