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

Dav*_*rth 38 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-现场

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

en:

  hello: 'hello'

  hello_world: 'hello world'



es:

  hello_world: 'hola mundo'
Run Code Online (Sandbox Code Playgroud)

当我执行此代码时:

I18n.t :hello, :locale => :es
Run Code Online (Sandbox Code Playgroud)

Rails返回"hello"而不是"缺少翻译"的跨度.

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

WTK*_*WTK 151

Nowdays没有必要使用单独的宝石I18N,在普通的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'}
Run Code Online (Sandbox Code Playgroud)

  • @AlexeyZakharov那取决于你正在使用的Rails版本.最初的问题是在**Rails 2.3.5**的背景下,而这个答案与**Rails 3.0.6相关** (3认同)

Jim*_*nke 19

如果您使用的是Rails 2,只要您使用最新的I18n gem,请将其添加到初始化程序:

I18n.backend.class.send(:include, I18n::Backend::Fallbacks)
Run Code Online (Sandbox Code Playgroud)

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

I18n.fallbacks.map('es' => 'en')
Run Code Online (Sandbox Code Playgroud)