10 OctI18n in Javascript files with Rails 3

Monday, 10 October 2011 — 09:03

With all the new techniques in Rails 3 for UJS, i was expecting an easiest way for also integrating I18n in javascript files (I mean real javascript files, not javascript templates). I was expecting for instance, the same way we can create css.erb files, i could do the same with js files. But this doesn’t seem to work. So we need to resort to external libs. In this case this gem was of tremendously help. Let’s see in detail:

1. Add this to your Gemfile (i like to add the link for further reference):

# https://github.com/fnando/i18n-js
gem "i18n-js"

2. Install the gem

bundle install

3. Set it up with this command. We will get a i18n-js.yml in our config file

rake i18n:js:setup

4. I recommend you edit the file and export just what you need. This is mine for instance, as i only need en and es files:

translations:
    - file: "app/assets/javascripts/i18n/translations.js"
      only: ['en.*', 'es.*']

IMPORTANT NOTE: Format here is important. Make sure the “only” line is perfectly tabbed under “f” letter of “file” line

5. Generate javascript file for specified languages. In development all the changes you make to your language files, will be automatically available in your javascript file. So i recommend you add this as part of your deployment to production scripts

rake i18n:js:export

6. Make js file available. Add this to your application.js (add the language file you generated, in my case translations)

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

7. We’re almost done. We only need an additional step for loading locale and have it available from javascript file. We need to know which is user’s locale. We will make this possible adding this to our application.html.erb file before any other javascript file:

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

8. Now we’re ready!. You will have I18n available with commands like:

I18n.t("scope.literal")

Find more options available on author’s gem website here

Ger

Comentarios

Añade tu comentario




(textile habilitado)
Negrita: *Google*
Enlace: "google.com":http://www.google.com
Imagen: !http://ggomeze.com/images/avatar.png!

ó Cancelar