/ internationalization

Access Rails locale in Javascript

For displaying flash messages and other informative messages, we generally use Internationalization (I18n) in rails.

Sometimes we also need to write similar messages again in javascript/coffeescripts which can be difficult to manage if these message changes. And also it doesnt follow the concept of DRY.

To follow DRY, we need to make rails locales available in javascript.

One way to do it is to declare a global variable and have all locales saved to it as Javascript Object.

This is what we did in our project:

Added following code in application layout:

For HAML -

 window.I18n = #{I18n.backend.send(:translations).to_json.html_safe}

For ERB -

 window.I18n = <%= I18n.backend.send(:translations).to_json.html_safe %>

With this, now you can access locale using

 I18n['en']['alpha']['bravo'];
OR
I18n.en.alpha.bravo; 

You can also create a helper method like:

  def current_translations
    @translations ||= I18n.backend.send(:translations)
    @translations[I18n.locale].with_indifferent_access
  end

and use it in layout like:

 window.I18n = #{current_translations.to_json.html_safe}

Now, you can use locale using:

 I18n['alpha']['bravo'];
OR
I18n.alpha.bravo;

Thanks.