如何向 I18n 动态添加值? [英] How to add values dynamically to I18n?

查看:85
本文介绍了如何向 I18n 动态添加值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 rails 应用程序中有很多 yml,我想将其中一些放在其他服务中,以便我可以从多个地方调用它.此调用的响应将是一个哈希值.

I have many ymls in my rails app, and i want to put some of them in other service, so that i can call this from multiple places. the response of this call will be a hash.

{"en" : 
  {"test" : 
    {"text1" : "hi english"},
    {"text2" : "mambo number %{num}"}
  },
 "es" : 
  {"test" : 
    {"text1" : "hi espaniol"},
    {"text2" : "mamboes numeros %{num}"}
  }
}

有什么方法可以将该哈希加载到 I18n 翻译中喜欢

is there a way i can load that hash into I18n translations like

I18n.add_translations(some_hash)

所以我可以访问它们

I18n.t("test.text1")
I18n.t("test.text2", :num => 5)

我怎样才能实现它?

推荐答案

肮脏的方式

您可以通过自定义模块或 gem 覆盖 I18n::Backend::Base 中的 load_translation 方法,或者 --cough --monkey patching --cough -- 从不同来源获取翻译,这让我觉得很脏,但我想你可以在进一步尝试之前尝试一下.

You could override the load_translation method in I18n::Backend::Base through a custom module or gem or -- cough -- monkey patching -- cough -- to fetch the translations from different sources, it feels dirty to me but I guess you could try experimenting with that before going further.

https://github.com/svenfuchs/i18n/blob/master/lib/i18n/backend/base.rb#L13

更改 I18n 后端

您可以创建一个不同的 I18n 后端来实现预期的行为,并通过初始化程序将其连接到 I18n.我假设localeapp 和phraseapp 之类的工具就是这样做的.在 I18n::Config

You can create a different I18n Backend that implements the expected behaviour and hook it up to I18n through an initializer. I'm assuming that's how tools like localeapp and phraseapp do it. There is a method just for that in I18n::Config

https://github.com/svenfuchs/i18n/blob/master/lib/i18n/config.rb#L23

所以你可以在初始化程序中做到这一点

So you can just do this in an initializer

I18n.backend = MyAwesomeI18nBackend.new

好处是你可以将多个后端链接在一起

The good thing is that you can chain multiple backends together

I18n.backend = I18n::Backend::Chain.new(MyAwesomeI18nBackend.new)

它确保您仍然可以访问默认翻译后端或其他自定义后端.

It makes sure you still have access to the default translation backends or other custom backends.

参考资料

Ryan 在过去的几天里做了一个很棒的 Railscast,解释了如何更改后端.它有点过时,但它可以让您很好地了解需要做什么.

Ryan made a great railscast back in the days explaining how to change backends. It's a bit outdated but it gives you a good idea of what needs to be done.

I18n 后端

如果您的翻译与保存在数据库中的某些数据相关,您也可以使用 globalize 来处理这些数据.

If your translations are related to some data saved in a database, you could also use globalize to handle those.

https://github.com/globalize/globalize

Dima 的更简单方法

如果您有散列,则可以使用默认后端的 store_translation 方法从该散列加载翻译.

If you have a hash, you can use the default backend's store_translation method to load translations from that hash.

I18n.backend.store_translations(:en, {test: "YOOOOOHHHHHOOOO"})

这篇关于如何向 I18n 动态添加值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆