http://guides.rubyonrails.org/i18n.html#setting-来自域名的区域设置
适用于.de或其他域。但对于英语域,我使用的是en.yml。我试图在我的应用程序控制器中实现一个异常,如下所示:
if I18n.available_locales.map(&:to_s) == "co.uk"
I18n.locale = "en"
end
但这行不通。我不想通过默认语言环境来实现这一点,这是我现在想到的唯一解决方案。
如果我在.co.uk域上,而不将默认区域设置为en,我如何告诉rails使用"en"区域设置?
您链接到的文档建议使用以下方法
before_action :set_locale
def set_locale
I18n.locale = extract_locale_from_tld || I18n.default_locale
end
def extract_locale_from_tld
parsed_locale = request.host.split('.').last
I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil
end
请尝试使用此选项。它更干净、更容易理解:
before_action :set_locale
...
private
def set_locale
parsed_locale = request.host.split('.').last
case parsed_locale
when 'de' then Il8n.locale = :de
when 'fr' then Il8n.locale = :fr
...
else
I18n.locale = :en #this is now your 'default'
end
end