【问题标题】:Rails I18n Cascading - how to get it to workRails I18n Cascading - 如何让它工作
【发布时间】:2013-08-29 12:04:21
【问题描述】:

我在this blogpost from Sven Fuchs 中读到了 I18n 的级联可能性,但我无法让它工作。

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

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 cascade rails-i18n


    【解决方案1】:

    所以,终于搞定了。

    问题是,默认情况下不包含级联模块,因此您必须自己包含它。 不幸的是,似乎没有预定义的配置选项(如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"
    

    它也适用于lazy lookups:

    # 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"
    

    【讨论】:

    • 非常有帮助/有用。感谢您回答您自己的问题!
    【解决方案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
    

    此解决方案也是 recommended way by Sven Fuchs,并已使用 Rails 4.0.4 进行测试。

    【讨论】:

    • 我记得我曾尝试过类似的解决方案,但遇到了一些麻烦,尽管一开始看起来很有希望。不过,我没有使用 skip_root 选项,所以这可能会奏效。你知道这个选项的实际作用吗?
    • 考虑级联机制的实现(cascade.rb) 我想说的是 skip_root 选项注意循环遍历 I18n 键的范围至少运行两次(看看 while条件)如果有足够大的范围再次切片并且在第一次迭代期间没有返回结果。现在,当我深入研究这一点时,我真的看不出这个选项有什么意义——我可能会考虑在一些测试后再次删除这个选项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    • 1970-01-01
    • 2012-08-14
    • 2012-02-11
    • 2017-03-08
    相关资源
    最近更新 更多