Rails: Internationalization of Javascript Strings?

JavascriptRuby on-RailsInternationalization

Javascript Problem Overview


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.

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

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?

Javascript Solutions


Solution 1 - Javascript

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;

Solution 2 - Javascript

Balibu is abandoned. Use i18n-js: https://github.com/fnando/i18n-js

Solution 3 - Javascript

Ryan's solution above is perfect, except the backend needs to be initialized if it hasn't been already.

I18n.backend.send(:init_translations) unless I18n.backend.initialized?
# now you can safely dump the translations to json

Solution 4 - Javascript

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: https://stackoverflow.com/questions/7761540/encoding-issues-in-javascript-files-using-rails-asset-pipeline

Solution 5 - Javascript

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!

Solution 6 - Javascript

Another option that could be helpful:

Supposing that you have a model Language (slug) that contains all your available languages. It handles the cases when a there's a missing translation (it's replaced by the default locale version)

#assets/javascript/i18n.js.erb

<%
@translator = I18n.backend
@translator.load_translations

translations = {}
Language.all.each do |l|
	translations[l.slug] = @translator.send(:translations)[l.slug.to_sym]
end

@translations = translations

%>
window.I18n = <%= @translations.to_json.html_safe %>

window.I18n.t = function(key){
	if(window.I18n[current_locale]){
		el = eval("I18n['"+current_locale+"']." + key);
	}
	if(window.I18n[default_locale] && typeof(el) == 'undefined'){
		el = eval("I18n['"+default_locale+"']." + key);
	}
	if(typeof(el) == 'undefined'){
		el = key;
	}
	return el;
};

#views/layout/application.html.erb

...
<%= javascript_tag "var current_locale = '#{I18n.locale.to_s}';" %>
<%= javascript_tag "var default_locale = '#{I18n.default_locale}';" %>
...

In you javascript code, you can translate like this:

// current_locale:fr , default_locale:en

// existing translation (in french) 
I18n.t('message.hello_world'); // => Bonjour le monde

// non-existing translation (in french) but existing in english 
I18n.t('message.hello_this_world'); // => Hello this world

// non-existing translation (french & english) 
I18n.t('message.hello_this_new_world'); // => message.hello_this_new_world

Hope that it helps!

Solution 7 - Javascript

Babilu is a Rails plugin that does this for you.

Solution 8 - Javascript

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"]

Solution 9 - Javascript

I18n-js is working great for me and i'd recommend it. If you use his rewrite branch then the plugin will include a /assets/i18n/filtered.js file which outputs exactly what @ryan-montgomery answered, without having to do anything yourself manually.

This way, you can use the same translations on the backend with Rails helpers t(:key) and using I18n.t('key') in Javascript on the frontend.

Solution 10 - Javascript

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/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt RogishView Question on Stackoverflow
Solution 1 - Javascriptrmontgomery429View Answer on Stackoverflow
Solution 2 - JavascriptFelipe Elias PhilippView Answer on Stackoverflow
Solution 3 - Javascriptlife_like_weedsView Answer on Stackoverflow
Solution 4 - Javascriptuser1026130View Answer on Stackoverflow
Solution 5 - JavascriptVince V.View Answer on Stackoverflow
Solution 6 - JavascriptSimoView Answer on Stackoverflow
Solution 7 - JavascriptsblomView Answer on Stackoverflow
Solution 8 - JavascriptmaclerView Answer on Stackoverflow
Solution 9 - Javascriptrobbie613View Answer on Stackoverflow
Solution 10 - JavascriptJohann EchavarriaView Answer on Stackoverflow