Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

ruby on rails - 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.

question from:https://stackoverflow.com/questions/2324398/fall-back-to-default-language-if-translation-missing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...