1

我在Sven Fuchs 的这篇博文中读到了 I18n 的级联可能性,但我无法让它发挥作用。

我尝试将博文中提到的代码放入应用程序控制器和初始化程序中,我还尝试传递级联选项,就像模块本身的评论中提到的那样,但似乎没有任何效果。

是否有人对如何在 Rails 4 应用程序中启动和运行 I18n 级联有任何提示或工作示例?

4

2 回答 2

3

所以,终于得到了这个工作。

问题是,默认情况下不包含级联模块,因此您必须自己包含它。不幸的是,似乎没有预定义的配置选项(例如 with config.i18n.fallbacks,但如果我错了请纠正我),因此您必须手动包含它:

# config/application.rb
module NameOfMyApp
  class Application < Rails::Application
    # some config code here
    I18n.backend.class.send(:include, I18n::Backend::Cascade)
    # more config code
  end
end

之后,如果您将cascade: true选项传递给 translate-helper,它将起作用。

一个例子

考虑您的en.yml文件中有以下几行:

# config/locales/en.yml
en:
  title: 'Default application title'
  subtitle: 'Default application subtitle'
  footertext: 'Default text for footer'

  accounts:
    title: 'Default accounts title'
    subtitle: 'Default accounts subtitle'

    index:
      title: 'Accounts index title'

在您的观点中,您可以这样使用它:

# app/views/account/index.html.erb
<%= t('accounts.index.title', cascade: true) %> # => "Accounts index title"
<%= t('accounts.index.subtitle', cascade: true) %> # => "Default accounts subtitle"
<%= t('accounts.index.footertext', cascade: true) %> # => "Default text for footer"

它也适用于惰性查找

# app/views/account/index.html.erb
<%= t('.title', cascade: true) %> # => "Accounts index title"
<%= t('.subtitle', cascade: true) %> # => "Default accounts subtitle"
<%= t('.footertext', cascade: true) %> # => "Default text for footer"
于 2013-09-17T11:55:24.917 回答
2

已接受答案的一些附加信息(这帮助我很好地朝着正确的方向前进)。

如果您还希望级联查找成为翻译助手的默认行为,一种方法是覆盖翻译方法。这样做可以尽可能少地进行操作以使其正常工作。这个解决方案很可能也应该向上兼容——只要翻译助手在方法签名等方面没有太大变化。

# e.g. in config/initializers/i18n.rb
# monkey-patch to let I18n.translate (and its alias 't') cascade for keys by default
ActionView::Base.class_eval do
  def translate(key, options = {})
    super(key, options.merge({ cascade: { skip_root: false } }))
  end
  alias t translate
end

此解决方案也是Sven Fuchs 推荐的方法,并已使用 Rails 4.0.4 进行了测试。

于 2014-04-08T11:26:28.417 回答