Rails:Javascript 字符串的国际化?

所以,我们现有的 Rails 2.3.5 应用程序根本不支持国际化.现在,我对 Rails I18n 的东西非常熟悉,但是我们在 /javascripts/ 中有很多输出字符串.我不是这种方法的忠实拥护者,但不幸的是,现在修复它为时已晚.

So, we have an existing Rails 2.3.5 app that does not support Internationalization at all. Now, I'm well familiar with Rails I18n stuff, but we have a LOT of output strings inside /javascripts/. I'm not a huge fan of this approach, but unfortunately it is too late to fix it now.

我们如何将存储在 Rails 应用程序中的 JS 文件中的字符串国际化?Rails 甚至不提供 JS 文件...

How might we internationalize strings stored in JS files in a Rails app? Rails doesn't even serve the JS files...

我想我总是可以让 Rails 应用程序提供 JS 文件,但这似乎很糟糕.有没有插件可以做到这一点?

I'm thinking I could always have the Rails app serve up the JS files, but that seems pretty gross. Are there plugins to do this?

推荐答案

为什么不做一些简单的事情:

Why not something simple like:

<script type="text/javascript">
  window.I18n = <%= I18n.backend.send(:translations).to_json.html_safe %>
</script>

然后在 JS 中你可以这样做:

Then in JS you can do things like:

I18n["en-US"]["alpha"]["bravo"];

我已经将我的包裹在一个应用程序助手中.

I've wrapped mine in an application helper.

def current_translations
  @translations ||= I18n.backend.send(:translations)
  @translations[I18n.locale].with_indifferent_access
end

然后我在 application.html.erb 中的调用如下所示:

Then my call in my application.html.erb looks like this:

<script type="text/javascript">
  window.I18n = <%= current_translations.to_json.html_safe %>
</script>

这使您不必知道 JavaScript 中的当前语言环境.

This allows you to avoid having to know the current locale in JavaScript.

I18n["alpha"]["bravo"];

或者

I18n.alpha.bravo;

相关文章