Rails:Javascript字符串的国际化? [英] Rails: Internationalization of Javascript Strings?
问题描述
因此,我们有一个现有的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?
推荐答案
为什么不像这样简单?
<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;
这篇关于Rails:Javascript字符串的国际化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!