【问题标题】:Rails i18n how to get all values for a certain key?Rails i18n 如何获取某个键的所有值?
【发布时间】:2013-01-16 17:49:29
【问题描述】:

在 Rails i18n 中,如何使用以下方法获取某个键的所有值:

translations = I18n.backend.send(:translations)

获取所有密钥

我需要能够获得一个特定部分,例如只返回“home”下的所有内容

en:
  home:
    test: test

【问题讨论】:

    标签: ruby-on-rails-3 key key-value rails-i18n


    【解决方案1】:

    设置I18n.locale 然后执行I18n.t 工作正常,例如:

    def self.all_t(string)
      I18n.locale = :en
      en = I18n.t("pages.home.#{string}")
      I18n.locale = :fr
      fr = I18n.("pages.home.#{string}")
      [en, fr]
    end
    

    【讨论】:

      【解决方案2】:

      默认的 I18n 后端是 I18n::Backend::Simple,它不会向您公开翻译。 (I18.backend.translations 是受保护的方法。)

      这通常不是一个好主意,但是如果您确实需要此信息并且无法解析文件,则可以扩展后端类。

      class I18n::Backend::Simple
        def translations_store
          translations
        end
      end
      

      然后您可以调用I18n.backend.translations_store 来获取已解析的翻译。您可能不应该将此作为一项长期策略,但它会立即为您提供所需的信息。

      【讨论】:

        【解决方案3】:

        I18n.backend.send(:translations) 的返回值只是一个哈希值,因此您只需传入适当的键即可访问子集。

        例如如果你有:

        en:
          foo:
            bar:
              some_term: "a translation"
              some_other_term: "another translation"   
        

        然后就可以得到bar下的hash子集了:

        I18n.backend.send(:translations)[:en][:foo][:bar]
        #=> { :some_term=>"a translation", :some_other_term => "another translation"}
        

        【讨论】:

        • 感谢我同时发现 I18n.t('home') 也有效
        • 很好,谢谢!这对我很有用,因为我正在寻找一种获取实际键名的方法。
        猜你喜欢
        • 2011-11-15
        • 1970-01-01
        • 1970-01-01
        • 2017-10-02
        • 1970-01-01
        • 2023-01-17
        • 1970-01-01
        • 1970-01-01
        • 2020-09-15
        相关资源
        最近更新 更多