如何使用 i18n & rails 配置语言环境别名?

How to configure locale aliases using i18n & rails?

我正在开发一个 rails 应用程序 (3.2.13),该应用程序正在被翻译成多种语言,包括挪威语(3 种可用语言之一)。在 public 页面上,应用程序使用浏览器的语言设置来设置区域设置。

大多数浏览器提供 3 种独立的挪威简码:nonbnn。我们的翻译是 nb,但我认为如果 nonn 也默认为 nb 会更好。这样,如果用户的浏览器语言首选项设置为 no 然后 en,应用程序将尝试首先提供 nb 挪威语,而不是直接跳到英语。

是否可以为 i18n gem 配置一个 "language aliases" 的列表,像这样?

 config.i18n.available_locales = [:sv, :en, :nb, :da, :fi]
 config.i18n.aliased_locales = [:nb <= :no, :nb <= :nn]

简答

查看后备方案

initializers 中创建一个文件,例如 i18n_fallbacks.rb

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

Here the reference

相关的东西

您甚至可以设置多个回退,它们将按照指定的相同顺序执行:

例如:

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

您得到以下内容:

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"

在最新的 i18n gem (0.7.0) 中,我发现有必要像这样定义后备语言环境(在 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

您还需要在所有 config/environments/*.rb 个文件中设置 config.i18n.fallbacks = true