If you follow the I18N Rails Guide, all generated links contain the locale parameter (localhost/en/about, localhost/fr/about). This is because we use the method default_url_options
to always add the Locale parameter :
def default_url_options(options={})
{ :locale => I18n.locale }
end
Is it possible to remove the locale parameter from the generated url when the locale is unknown or the default one ?
What I need :
- Locale unknown :
mysite/about
- Locale en :
mysite/about
(and not localhost/en/about
)
- Locale fr :
mysite/fr/about
I tried to only set the locale if it was not the default one, but the result is that the generated links never contain the locale parameter...
I tried many things like this one
def default_url_options(options={})
if I18n.locale == :fr
{ :locale => I18n.locale }
else
{ :locale => nil }
end
end
Whole code :
ApplicationController.rb :
before_filter :set_locale
def set_locale
I18n.locale = params[:locale]
end
def default_url_options(options={})
{ :locale => I18n.locale }
end
routes.rb
scope "(:locale)", :locale => /en|fr/ do
match 'about' => 'static_pages#about', :via => :get
match 'contact' => 'static_pages#contact', :via => :get
match '/' => 'search#index', :as => :search
end
root :to => 'search#index'
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…