问题
I am working on a rails app (3.2.13) that is being translated into several languages, including (one of the 3 available flavours of) Norwegian. On public pages, the app uses the browser's language settings to set locale.
Most browsers offer 3 separate Norwegian shortcodes: no
, nb
& nn
. The translations we have are in nb
, but I think it would be best if no
& nn
also defaulted to nb
. That way, if a user's browser language preferences were set to no
then en
, the app would try to supply nb
Norwegian first, instead of skipping straight to English.
Is it possible to configure a list of "language aliases" for the i18n gem, something like this?
config.i18n.available_locales = [:sv, :en, :nb, :da, :fi]
config.i18n.aliased_locales = [:nb <= :no, :nb <= :nn]
回答1:
Short answer
Take a look to the fallbacks
Create a file in initializers
like i18n_fallbacks.rb
config.i18n.fallbacks = {:no => [:nb], :nn => [:nb]}
Here the reference
Things related
You can even set multiple fallbacks, and they will be taken in the same order as specified:
for instance:
config.i18n.default_locale = :de
config.i18n.fallbacks = {:de => [:en,:es]}
de.yml
:de:
greeting: Hallo
en.yml
:en:
foo: bar
es.yml
:es:
bar: baz
You get the following:
I18n.t :greeting # found in de.yml, no fallback
# => 'Hallo'
I18n.t :foo # not in :de, try in :en and found
# => "bar"
I18n.t :bar # not in :de, try in :en and in :es
# => "baz"
I81n.t :other # not found anywhere, note the message delivers not found for the current locale:
# => "translation missing: de.other"
回答2:
In latest i18n gem (0.7.0) I have found it necessary to define fallback locales like this (in config/application.rb
):
# Custom I18n fallbacks
config.after_initialize do
I18n.fallbacks = I18n::Locale::Fallbacks.new(at: :"de-DE", ch: :"de-DE", gb: :"en-US")
end
You also need to set config.i18n.fallbacks = true
in all config/environments/*.rb
files.
来源:https://stackoverflow.com/questions/28049171/how-to-configure-locale-aliases-using-i18n-rails