Rails i18n, how to get all values ​​for a specific key?

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

translations = I18n.backend.send(:translations) 

get all keys

I need to be able to get a specific section, for example, return only everything to "home"

 en: home: test: test 
+8
ruby-on-rails-3 key-value key rails-i18n
source share
3 answers

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

eg. if you have:

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

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

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

The default I18n backend is I18n::Backend::Simple , which does not provide translations for you. ( I18.backend.translations is a protected method.)

This is usually not a good idea, but if you really need this information and cannot parse the file, you can extend the backend class.

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

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

+5
source share

Setting up I18n.locale , then running I18n.t will be fine, for example:

 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 
0
source share

All Articles