如果缺少翻译,则回退到默认语言

时间:2010-02-24 07:48:10

标签: ruby-on-rails internationalization

在一个国际化的Rails(2.3.5)应用程序中,我想显示默认语言环境的翻译,而不是“翻译丢失” - 这是一张票,但它似乎还在等待:

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

例如(取自票证),带有两个翻译文件,en.yml和es.yml:

en:

  hello: 'hello'

  hello_world: 'hello world'



es:

  hello_world: 'hola mundo'

执行此代码时:

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

Rails返回“hello”而不是“缺少翻译”的范围。

由于故障单仍处于待处理状态,我该如何实现此功能?我知道我可以通过并改变所有我的I18n.t调用以获得:default选项,但如果我能避免它,我宁愿不必浏览所有视图!因为它是一个补丁,我想我可以将它应用于Rails冷冻宝石,但如果可以,我宁愿避免使用它。

3 个答案:

答案 0 :(得分:149)

现在没有必要使用单独的i18n gem,在普通的Rails 3.0.6及以上版本(包括5.0)上安装,fallbacks值可以以下之一< /强>:

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

答案 1 :(得分:19)

如果您使用 Rails 2 ,只要您使用最新的I18n gem,请将其添加到初始值设定项中:

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

然后你可以像这样添加你的后备:

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

答案 2 :(得分:0)

我认为最简单的方法是将其添加到配置文件中(例如,application.rb):

 config.i18n.fallbacks = true

它对于en-US,en-CA等区域语言环境非常有用,因为它们可以自动回退到语言环境。

正如吉米指出的那样,你甚至可以通过以下方式改变回退机制:

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