Rails: Internationalization of Javascript Strings?

Matt Rogish picture Matt Rogish · Apr 23, 2010 · Viewed 23.9k times · Source

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?

Answer

Ryan Montgomery picture Ryan Montgomery · May 16, 2012

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;