How to use I18n from controller in Rails
13,250
In controller you use it like this
I18n.t 'controllers.admin.pet.treated'
Using t()
directly enables lazy loading:
t(".treated") #loads from key: controllers.admin.pet.treated
![Iván Cortés Romero](https://lh4.googleusercontent.com/-LKQUV9yTvkc/AAAAAAAAAAI/AAAAAAAAABM/3umg80-LeJM/photo.jpg?sz=256)
Author by
Iván Cortés Romero
Updated on June 12, 2022Comments
-
Iván Cortés Romero about 2 years
I have a PetsController in which a flash message is setted. Something like this:
class PetsController ... def treat_dog #do somthing flash[:success] = 'Your dog is being treated.' end ... end
this controller belongs to Admin, so it is located at:
app/controllers/admin/pets_controller.rb
. I will use I18n, so I replaced the string in controller witht('controllers.admin.pet.treated')
, then,I wrote this yml:en: controllers: admin: pet: treated: "Your dog is being treated."
located at:
config/locales/controllers/admin/pet/en.yml
and it did not work. I have attempted locating it atconfig/locales/controllers/admin/pets/en.yml
,config/locales/controllers/admin/en.yml
config/locales/controllers/en.yml
and none of these worked, the translation is not found.How can I use a translation from this controller?
-
Iván Cortés Romero over 8 yearsI forgot write the simple quotation marks in the question,but I really used it
-
Iván Cortés Romero over 8 yearsthe yml's located at
config/locales/en.yml
are used to set the general or generic tranlations.When you have a lot of tranlations, you can locate them with the same hierarchy order thanview
andcontroller
tree. -
Sergio Tulentsev over 8 years@IvánCortésRomero: hah, didn't know about it! However, do read that guide. It mentions that nested files are not loaded by default and how to enable it.
-
Iván Cortés Romero over 8 yearsI did'n know about that configuration,so I have checked my
config/application.rb
and I found already this line. However, thank youa lot. -
Iván Cortés Romero over 8 yearsYes, I have found that by convention, in controllers I18n translation must be used with I18n.t 'key' instead of t('key') but this last must work too. In my case, exchange it works for me. Thanks Mahesh.
-
dft over 7 yearsAs explained in the guides guides.rubyonrails.org/i18n.html#lazy-lookup you could probably simplify that with lazy lookups using the helper like this
t('.treated')
-
Augusto Samamé Barrientos almost 6 yearsBear in mind that both I18n.t 'key' and t('key') will work in controllers, but only the t('key') helper supports lazy loading via the t('.key') shortcut.