【问题标题】:Rails: set local to "en" when .co.uk domainRails:当 .co.uk 域时,将本地设置为“en”
【发布时间】:2014-07-11 09:50:07
【问题描述】:

http://guides.rubyonrails.org/i18n.html#setting-the-locale-from-the-domain-name

适用于 .de 或其他域名。 但是对于说英语的域,我使用的是 en.yml。我试图在我的应用程序控制器中实现这样的异常:

if I18n.available_locales.map(&:to_s) == "co.uk"
  I18n.locale = "en"
end

但这行不通。 我不想通过默认语言环境来执行此操作,这是我现在想到的唯一解决方案。

如果我在 .co.uk 域上而不将默认语言环境设置为 en,如何告诉 Rails 使用“en”语言环境?

【问题讨论】:

  • 您在使用多少个语言环境?
  • 目前只有 de 和 en - 但未来还会有更多(.es、.fr、.ro)

标签: ruby-on-rails rails-i18n


【解决方案1】:

您链接到的文档推荐了以下方法

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

【讨论】:

  • 工作,但在 de 上,我得到这个:“未初始化常量 ApplicationController::Il8n” for line “when 'de' then Il8n.locale = :de”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-26
  • 1970-01-01
  • 1970-01-01
  • 2020-06-06
  • 2011-05-15
相关资源
最近更新 更多