【问题标题】:Locale fallback from country to language without having to define each individually从国家到语言的区域设置回退,无需单独定义每个语言
【发布时间】:2012-11-13 22:29:19
【问题描述】:

我正在使用默认的 rails I18n 本地化一个应用程序,并将 globalize3 作为后端。

是否可以在自动转到默认回退之前设置带有国家代码(即:fr-CA)的区域设置以回退到其特定语言(:fr)?我知道可以使用

手动设置每个语言环境/国家/地区
config.i18n.fallbacks = {'fr-CA' => 'fr'}

但最好不必手动添加每个后备并自动执行此行为。

【问题讨论】:

  • 在任何现代 Rails(比如说 6)中,如果启用了回退,特定国家/地区的语言环境总是回退到通用语言语言环境。无需手动操作。

标签: ruby-on-rails localization fallback globalize3 rails-i18n


【解决方案1】:

为了实现这一点,我有一个初始化器

I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)

请参阅the source code 了解更多信息。

编辑:

这提醒了我,ActionView LookupContext 中有 an annoying bug,这会阻止它用于本地化视图(尽管它适用于区域设置文件)。我看还没有修好。基本上,如果您有任何本地化视图(例如帮助页面,由于它们的长度不适合存储在语言环境文件中),那么 fr-CA 语言环境将不会回退到称为帮助的视图。 fr.html.erb。您必须将文件命名为 help.fr-CA.html.erb ,这就是我所做的,用另一个初始化程序猴子修补 LookupContext,有点像这样:

module ActionView
  class LookupContext
    # Override locale= to also set the I18n.locale. If the current I18n.config object responds
    # to original_config, it means that it's has a copy of the original I18n configuration and it's
    # acting as proxy, which we need to skip.
    def locale=(value)
      if value
        config = I18n.config.respond_to?(:original_config) ? I18n.config.original_config : I18n.config
        config.locale = value[0,2] # only use first part of the locale in lookups
      end
      super(@skip_default_locale ? I18n.locale : default_locale)
    end
  end
end

另一个编辑:请注意,补丁相当粗糙,破坏了完整的语言环境查找,直接针对语言。如果您还需要完全匹配的视图(语言区域),您需要改进我的代码!

【讨论】:

  • 谢谢。我没有本地化视图,所以我只需要初始化器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多