Unclear how to use "config.i18n.fallbacks" in Rails 5
Asked Answered
M

2

6

I want the translations on my website to fallback to English when a translation isn't found. How to do that?

There're 2 ways I know of, but it's unclear which should be used with Rails 5 and which has already become deprecated:

## config/appplication.rb

# 1
config.i18n.fallbacks = [:de, :fr, :en]

# 2
config.i18n.fallbacks = true

There's nothing about that in the documentation either.

Meliamelic answered 26/7, 2018 at 13:44 Comment(1)
The Rails guide on configuration contains a section on I18n configuration and fallbacks: guides.rubyonrails.org/v5.2.0/configuring.html#configuring-i18nFuniculus
L
5
config.i18n.default_locale = :de
config.i18n.available_locales = [:de, :en, :fr]
config.i18n.fallbacks = [:en, :de]

That means. If someone uses French, and a translation is missing, the fallback is English, when the English translation is also blank, then i18n returns German.

Lissome answered 26/7, 2018 at 14:32 Comment(0)
T
1

If you're not sure, I always recommend to look into the source code.

    def self.init_fallbacks(fallbacks)
      include_fallbacks_module

      args = \
        case fallbacks
        when ActiveSupport::OrderedOptions
          [*(fallbacks[:defaults] || []) << fallbacks[:map]].compact
        when Hash, Array
          Array.wrap(fallbacks)
        else # TrueClass
          [I18n.default_locale]
        end

      I18n.fallbacks = I18n::Locale::Fallbacks.new(*args)
    end

With this in mind, we know now

# sets the fallback to the default local
config.i18n.fallbacks = true

# sets several fallbacks
config.i18n.fallbacks = [:en, :de]

https://github.com/rails/rails/blob/master/activesupport/lib/active_support/i18n_railtie.rb#L92-L106 https://github.com/ruby-i18n/i18n/blob/master/lib/i18n/locale/fallbacks.rb#L27-L51

Tichon answered 3/1, 2021 at 22:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.