-->

I18n locale disregarding fallbacks

2019-07-18 16:26发布

问题:

I asked a previous question regarding locale-setting. I am trying to set up fallbacks of various Norwegian languages to Norwegian Bokmal (:nb). The desired behaviour is that if a browser passes nn or no as locale requests, the I18n.locale will be set to either :nn or :no, and then in the absence of translations for these locales, :nb will be served to the browser.

Based on the answer to my previous question, I have this line in my application initialiser:

  config.i18n.default_locale    = :en
  config.i18n.fallbacks = {:nn => [:nb], :no => [:nb]}

In rails console, this gives me the following results:

> I18n.fallbacks
  => {:en=>[:en]} 

> I18n.fallbacks[:nn]
  => [:nn, :nb, :en] 

> I18n.fallbacks[:no]
  => [:no, :nb, :en] 

Using a browser that has only nn & no in the language list, this does not work- it falls back to the default locale of :en instead. Here's the request headers:

Accept-Language: "nn,no;q=0.5"

If I add :nb to the browser language stack, I am correctly served Norwegian content.

Is there something I am missing in this process?

回答1:

You need to set I18n.locale based on the browser setting.

def set_locale
  I18n.locale = extract_locale_from_accept_language_header
end

private

def extract_locale_from_accept_language_header
  request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
end

Taken from: http://guides.rubyonrails.org/i18n.html#setting-the-locale-from-the-client-supplied-information