41
votes

in an internationalised Rails (2.3.5) app, I'd like to show a translation from the default locale instead of "translation missing" - there's a ticket for it but it seems it's still pending:

https://rails.lighthouseapp.com/projects/8994/tickets/2637-patch-i18n-look-up-a-translation-with-the-default-locale-when-its-missed-with-another-specific-locale

For example (taken from the ticket), with two translation files, en.yml and es.yml:

en:

  hello: 'hello'

  hello_world: 'hello world'



es:

  hello_world: 'hola mundo'

When I execute this code:

I18n.t :hello, :locale => :es

Rails returns "hello" instead of a span with "translation missing".

As the ticket is still pending, how could I implement this functionality? I know I could go through and change all my I18n.t calls to have the :default option, but I'd rather not have to go through all the views if I can avoid it! As it's a patch, I suppose I could apply it to the Rails frozen gems, but I'd rather avoid that if I can.

3

3 Answers

158
votes

Nowdays there's no need for using separate i18n gem, on plain Rails 3.0.6 and above (5.0 included) installation, fallbacks value can be one of the following:

# application.rb

# rails will fallback to config.i18n.default_locale translation
config.i18n.fallbacks = true

# rails will fallback to en, no matter what is set as config.i18n.default_locale
config.i18n.fallbacks = [:en]

# fallbacks value can also be a hash - a map of fallbacks if you will
# missing translations of es and fr languages will fallback to english
# missing translations in german will fallback to french ('de' => 'fr')
config.i18n.fallbacks = {'es' => 'en', 'fr' => 'en', 'de' => 'fr'}
19
votes

If you are using Rails 2, provided that you use the latest I18n gem, add this to an initializer:

I18n.backend.class.send(:include, I18n::Backend::Fallbacks)

Then you can add your fallbacks like this:

I18n.fallbacks.map('es' => 'en')
0
votes

I think the easiest is to add this to your config files (eg. application.rb):

 config.i18n.fallbacks = true

It's very useful for regional locales like en-US, en-CA, etc. because they can fallback automatically to locale en.

As Jimmy points out, you can even alter the fallback mechanism with:

I18n.fallbacks.map('es' => 'en')