Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fall back to default language if translation missing

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.

like image 341
Dave Hollingworth Avatar asked Feb 24 '10 07:02

Dave Hollingworth


2 Answers

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'}
like image 164
WTK Avatar answered Nov 17 '22 00:11

WTK


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')
like image 19
Jimmy Stenke Avatar answered Nov 17 '22 00:11

Jimmy Stenke