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
For rails 3 applications you could do this:
Create a i18n.js.erb file and add it to your application.js. And add this piece of code into the file.
<%
@translator = I18n.backend
@translator.load_translations
@translations ||= @translator.send(:translations)[I18n.locale][:javascript]
%>
window.I18n = <%= @translations.to_json.html_safe %>
I also scope my translations to not have a huge javascript file. My scope is :javascript.
Hope it helps someone!
Babilu is a Rails plugin that does this for you.
Ryan solution is brillant.
But to not include the entire file you should use: @translations[I18n.locale].with_indifferent_access["alpha"]
instead of I18n.backend.send(:translations)["alpha"]
For applications like the one you described "that does not support Internationalization at all" and "is too late to fix it now" I wrote a very quick approach: the jQuery plugin Quick-i18n: https://github.com/katio/Quick-i18n demo (and how to use it): http://johannpaul.net/Quick-i18n/
Why not something simple like:
<script type="text/javascript">
window.I18n = <%= I18n.backend.send(:translations).to_json.html_safe %>
</script>
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
Then my call in my application.html.erb looks like this:
<script type="text/javascript">
window.I18n = <%= current_translations.to_json.html_safe %>
</script>
This allows you to avoid having to know the current locale in JavaScript.
I18n["alpha"]["bravo"];
Or
I18n.alpha.bravo;
Why not simply this in your Javascript file:
var a_message = "<%= I18n.t 'my_key' %>"
For this to work, you must add .erb to your Javascript file's extension.
You might also need to add the following line at the top of your Javascript file if you aren't using ruby >= 2.0.
<%# encoding: utf-8 %>
See the last comment of the accepted answer in this thread for more info: Encoding issues in javascript files using rails asset pipeline