简体   繁体   中英

How to use I18n from controller in Rails

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?

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
def treat_dog
    #do somthing
    flash[:success] = t('controllers.admin.pet.treated')
end

Put it into config/locales/en.yml and it should work (you may need to restart the server).

This guide should help clear the head about I18n. I'm giving link to relevant section, but read it in full: http://guides.rubyonrails.org/i18n.html#adding-translations

If you insist on using nested files, you need to enable it. Documentation says:

The default locale loading mechanism in Rails does not load locale files in nested dictionaries, like we have here. So, for this to work, we must explicitly tell Rails to look further:

# config/application.rb
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]

在回调中它应该是:

add_breadcrumb proc{ I18n.t('home_page') }, :root_path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM