【问题标题】:How to configure locale aliases using i18n & rails?如何使用 i18n 和 rails 配置语言环境别名?
【发布时间】:2015-01-20 15:30:46
【问题描述】:

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

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

是否可以为 i18n gem 配置“语言别名”列表,像这样?

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

【问题讨论】:

    标签: ruby-on-rails rails-i18n


    【解决方案1】:

    简答

    看看后备方案

    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"
    

    【讨论】:

    【解决方案2】:

    在最新的 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-05
      • 1970-01-01
      • 2012-07-05
      • 2019-04-23
      • 2012-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多