i18n后备,但只有那些明确说明

时间:2015-07-15 14:20:18

标签: ruby-on-rails internationalization

我的config / initializers / i18n.rb文件

require "i18n/backend/fallbacks"                                                                                                                                            
I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)                                                                                                              
I18n.fallbacks.map(:'en-US' => :en, :'fr-FR' => :fr, :'de-DE' => :de, :'es-ES' => :es, :'zh-CN' => :zh) 

但是现在缺少法语的东西将会减少英语,这是不希望的行为。如何仅针对特定区域设置具有特定的回退?

2 个答案:

答案 0 :(得分:0)

我最终得到了一种方法,它重载了所有方法来处理我想要的东西。我仍然希望那里有更直接的东西,但这是我能够工作的东西。

应用程序/助手/ i18n_helper.rb

module I18nHelper
  def translate(key, options={})
    mapping = MyApp::Application.config.locale_mapping
    super(key, options.merge(raise: true))
  rescue I18n::MissingTranslationData
    if mapping.has_key?(locale)
      super(key, options.merge(locale: mapping[locale]))
    else
      super(key, options)
    end
  end
  alias :t :translate
end

配置/初始化/ i18n.rb

module I18n
  class CustomFallbackExceptionHandler < ExceptionHandler
    def call(exception, locale, key, options)
      mapping = MyApp::Application.config.locale_mapping
      if mapping.has_key? locale
        I18n.t(key, options.merge(locale: mapping[locale]))
      else
        super
      end
    end
  end
end

I18n.exception_handler = I18n::CustomFallbackExceptionHandler.new

配置/ application.rb中

config.i18n.available_locales = [:'en-US', :'fr-FR', :'de-DE', :'es-ES', :'zh-CN', :en, :fr, :de, :es, :zh]
config.locale_mapping = {:'en-US' => :en, :'fr-FR' => :fr, :'de-DE' => :de, :'es-ES' => :es, :'zh-CN' => :zh}

答案 1 :(得分:0)

这在 Rails 到 6.1 中很棘手,因为您需要 beat the logic in the Railtie initializer,而后者非常想回退到 default_locale

要将默认后备语言环境设置为 nil,您需要使用以下代码:

config.i18n.default_locale = :en
config.i18n.fallbacks.defaults = [[]] # If you just write [], then default_locale is used
config.i18n.fallbacks.map = {
  :'en-US' => :en, 
  :'fr-FR' => :fr, 
  :'de-DE' => :de, 
  :'es-ES' => :es, 
  :'zh-CN' => :zh,
}

注意 #1:默认情况下,所有国家/地区变体(例如 en-US)将首先回退到语言(例如 en),如果您想以不同的方式回退,您只需要指定某些内容。所以基本上你的映射可以这样简化:

config.i18n.default_locale = :en
config.i18n.fallbacks.defaults = [[]] 
config.i18n.fallbacks.map = {}

让我们检查一下:

...> rails console
2.7.2 :001 > I18n.fallbacks["de-AT"] # Check what happens with Austrian German?
 => [:"de-AT", :de]

2.7.2 :002 > I18n.fallbacks[:fr]     # French should have no fallback!
 => [:fr]

注意 #2:我认为没有办法防止国家/地区变体回退到仅语言区域设置。

注意 #3:Some more subtleties in this answer.

相关问题