如何在 Rails 中从控制器使用 I18n
How to use I18n from controller in Rails
我有一个 PetsController,其中设置了一条闪现消息。像这样:
class PetsController
...
def treat_dog
#do somthing
flash[:success] = 'Your dog is being treated.'
end
...
end
此控制器属于管理员,因此位于: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.yml
、config/locales/controllers/admin/en.yml
config/locales/controllers/en.yml
其中 none 有效,未找到翻译。
如何使用此控制器的翻译?
在控制器中你可以这样使用它
I18n.t 'controllers.admin.pet.treated'
直接使用t()
启用延迟加载:
t(".treated") #loads from key: controllers.admin.pet.treated
def treat_dog
#do somthing
flash[:success] = t('controllers.admin.pet.treated')
end
将其放入config/locales/en.yml
,它应该可以工作(您可能需要重新启动服务器)。
本指南应该有助于理清有关 I18n 的问题。我给相关部分 link,但完整阅读:http://guides.rubyonrails.org/i18n.html#adding-translations
如果您坚持使用嵌套文件,则需要启用它。文档说:
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
我有一个 PetsController,其中设置了一条闪现消息。像这样:
class PetsController
...
def treat_dog
#do somthing
flash[:success] = 'Your dog is being treated.'
end
...
end
此控制器属于管理员,因此位于: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.yml
、config/locales/controllers/admin/en.yml
config/locales/controllers/en.yml
其中 none 有效,未找到翻译。
如何使用此控制器的翻译?
在控制器中你可以这样使用它
I18n.t 'controllers.admin.pet.treated'
直接使用t()
启用延迟加载:
t(".treated") #loads from key: controllers.admin.pet.treated
def treat_dog
#do somthing
flash[:success] = t('controllers.admin.pet.treated')
end
将其放入config/locales/en.yml
,它应该可以工作(您可能需要重新启动服务器)。
本指南应该有助于理清有关 I18n 的问题。我给相关部分 link,但完整阅读:http://guides.rubyonrails.org/i18n.html#adding-translations
如果您坚持使用嵌套文件,则需要启用它。文档说:
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