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
Share:
13,250
Iván Cortés Romero
Author by

Iván Cortés Romero

Updated on June 12, 2022

Comments

  • Iván Cortés Romero
    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 with t('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 at config/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
    Iván Cortés Romero over 8 years
    I forgot write the simple quotation marks in the question,but I really used it
  • Iván Cortés Romero
    Iván Cortés Romero over 8 years
    the 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 than view and controller tree.
  • Sergio Tulentsev
    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
    Iván Cortés Romero over 8 years
    I 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
    Iván Cortés Romero over 8 years
    Yes, 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
    dft over 7 years
    As 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
    Augusto Samamé Barrientos almost 6 years
    Bear 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.