Search code examples
ruby-on-rails-3keykey-valuerails-i18n

Rails i18n how to get all values for a certain key?


In Rails i18n, how to get all values for a certain key using the following:

translations = I18n.backend.send(:translations)

get all the keys

I need to be able to get a certain section for example only return everything under "home"

en:
  home:
    test: test

Solution

  • The return value of I18n.backend.send(:translations) is just a hash, so you can access a subset just by passing in the appropriate keys.

    e.g. if you have:

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

    Then you can get the the subset of the hash under bar with:

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