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

4

12

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
Bloodthirsty answered 1/2, 2013 at 12:4 Comment(0)
D
14

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"}
Dolli answered 1/2, 2013 at 13:29 Comment(2)
Thanks i found out in the meantime that I18n.t('home') works alsoBloodthirsty
Nice, thanks! this worked great for me as I was looking for a way to get the actual key name.Ophthalmoscope
K
5

The default I18n backend is I18n::Backend::Simple, which does not expose the translations to you. (I18n.backend.translations is a protected method.)

This isn't generally a good idea, but if you really need this info and can't parse the file, you can extend the backend class.

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

You can then call I18n.backend.translations_store to get the parsed translations. You probably shouldn't rely on this as a long term strategy, but it gets you the information you need right now.

Knowles answered 1/2, 2013 at 13:16 Comment(0)
E
1

Setting I18n.locale then doing I18n.t works fine, e.g.:

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
Elsewhere answered 28/2, 2018 at 12:28 Comment(0)
P
0

Late to the party here, but I just had to extract all the country codes from a Rails locale file, and the suggestions above did not work for Rails 6 and i18n 1.12.

Turns out that the translations method on I18n::Backend::Simple is now public, so we can now use : I18n.backend.translations(do_init: true) to retrieve the translations hash.

Therefore the home node mentioned above can be retrieved with : I18n.backend.translations(do_init: true)[:fr][:home]

Hope this helps

Praseodymium answered 13/2, 2023 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.