如何在Rails中使用控制器中的I18n

时间:2015-10-28 13:08:06

标签: ruby-on-rails controller internationalization rails-i18n

我有一个PetsController,其中设置了flash消息。像这样:

class PetsController

  ...

  def treat_dog
    #do somthing
    flash[:success] = 'Your dog is being treated.'
  end

  ...

end

此控制器属于Admin,因此它位于:app/controllers/admin/pets_controller.rb。我将使用I18n,所以我用t('controllers.admin.pet.treated')替换了控制器中的字符串,然后,我写了这个yml:

en:
  controllers:
    admin:
      pet:
        treated: "Your dog is being treated."

位于:config/locales/controllers/admin/pet/en.yml,但无效。我尝试在config/locales/controllers/admin/pets/en.ymlconfig/locales/controllers/admin/en.yml找到它 config/locales/controllers/en.yml 并且没有一个工作,没有找到翻译。

如何使用此控制器的翻译?

4 个答案:

答案 0 :(得分:14)

在控制器中你可以像这样使用它

I18n.t 'controllers.admin.pet.treated'

答案 1 :(得分:0)

def treat_dog
    #do somthing
    flash[:success] = t('controllers.admin.pet.treated')
end

答案 2 :(得分:0)

将它放入config/locales/en.yml并且它应该可以工作(您可能需要重新启动服务器)。

本指南应该有助于清除I18n的头脑。我将链接到相关部分,但请完整阅读:http://guides.rubyonrails.org/i18n.html#adding-translations

如果您坚持使用嵌套文件,则需要启用它。文档说:

  

Rails中的默认语言环境加载机制不会在嵌套字典中加载语言环境文件,就像我们在这里一样。因此,要实现这一点,我们必须明确告诉Rails进一步:

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

答案 3 :(得分:0)

In callback it should be:

add_breadcrumb proc{ I18n.t('home_page') }, :root_path
相关问题