如何避免在生成的 URL 中添加默认语言环境? [英] How to avoid adding the default Locale in generated URLs?
问题描述
如果您遵循 I18N Rails 指南,所有生成的链接都包含语言环境参数(localhost/en/about, localhost/fr/about).这是因为我们使用 default_url_options
方法总是添加 Locale 参数:
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
是否可以在语言环境未知或默认情况下从生成的url中删除语言环境参数?
我需要什么:
- 语言环境未知:
mysite/about
- 语言环境:
mysite/about
(而不是localhost/en/about
) - 语言环境:
mysite/fr/about
- Locale unknown :
mysite/about
- Locale en :
mysite/about
(and notlocalhost/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...
我试过很多类似的东西
def default_url_options(options={})
if I18n.locale == :fr
{ :locale => I18n.locale }
else
{ :locale => nil }
end
end
<小时>
完整代码:
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'
推荐答案
好吧,我明白多了.的确,你几乎做到了.
Ok I understand much better. Indeed, you almost did it.
你只需要一个非常有用的 Ruby 运算符:||
You just need a very useful operator in Ruby: ||
如果第一个值存在,则使用它,否则考虑第二个参数.
If the first value exists, it's used, otherwise the second argument is taken into account.
def set_locale
I18n.locale = params[:locale] || :en
end
这篇关于如何避免在生成的 URL 中添加默认语言环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!