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.
config.i18n.load_path sets the path Rails uses to look for locale files. Defaults to config/locales/*. {yml,rb}. config.i18n.raise_on_missing_translations determines whether an error should be raised for missing translations in controllers and views. This defaults to false. config.i18n.fallbacks sets fallback behavior for missing translations.
config.i18n.default_locale sets the default locale of an application used for i18n. Defaults to :en. config.i18n.enforce_available_locales ensures that all locales passed through i18n must be declared in the available_locales list, raising an I18n::InvalidLocale exception when setting an unavailable locale.
Default is an empty array. config.autoload_paths accepts an array of paths from which Rails will autoload constants. Default is an empty array. Since Rails 6, it is not recommended to adjust this.
config.i18n.enforce_available_locales ensures that all locales passed through i18n must be declared in the available_locales list, raising an I18n::InvalidLocale exception when setting an unavailable locale. Defaults to true.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With