Rails I18n Translations on the JavaScript

Recently, my user story demanded me to translate some text in raw JavaScript file. I know that I can easily use them in my .js.erb templates. But what about the Javascript files(.js)?

I18n.js is a small library to provide the Rails I18n translations on the JavaScript.

Steps for setting up i18n-js:

1) Add i18n-js gem to your Gemfile

gem "i18n-js", ">= 3.0.0.rc8"
bundle install

2) If you’re using the asset pipeline, add the following lines in app/assets/javascripts/application.js

//= require i18n
//= require i18n/translations

If you’re not using the asset pipeline, add the following lines in your application.html.erb (layout file)

<%= javascript_include_tag "i18n" %>
<%= javascript_include_tag "translations" %>

3) To export all translation files, run the following commands

rake i18n:js:export

4) Add the following lines in your application.html.erb (layout file)

<script type="text/javascript">
     I18n.defaultLocale = "<%= I18n.default_locale %>";
     I18n.locale = "<%= I18n.locale %>";
</script>

5) Finally, you can use translate your text in js file.

I18n.t("some.scoped.translation");

Note: Run the following command every time you have new translation in the .yml file

rake i18n:js:export

Comments