I18n and Javascript

Hi,

I have quite many pure javascript files (*.js) in my rails project.
Unfortunately some of those files contain strings to be translated. I
have just started using I18n in rails. I’d like to hear your feedback
about how you are translating your javascript files.

After some research, here are some approaches I found:

  1. Handle all your js files as filename.js.erb and use I18n tools like
    in normal templates

  2. Use different plugins, like Babilu for instance (http://
    tore.darell.no/posts/
    introducing_babilu_rails_i18n_for_your_javascript).

Thanks for your help!

Cheers,

hade

I’ve always had this doubt too. Has anyone a suggestion? How are you
handling it?

Regards

I had no experience about Babilu so I decided to go with the first
approach using filename.js.erb.

i) I created a new controller called js and moved all my translation-
needed *.js files under views/js and renamed them from *.js =>
*.js.erb

ii) Previously the *.js files were loaded from public/javascript, so I
needed to change this a bit. Now the moved *.js files are loaded from /
js/myclass.js

iii) And in my controller I’m also serving *.js files:

def index
respond_to do |format|
format.html
format.js
end
end

So basically I can now make translations like this:

// myclass.js

var MyClass = Class.create({

initialize: function() {
    this.stringToBeTranslated = <%= I18n.t 'header.translate_me'

%>

}

});

But I have no idea if this is the right way. Comments?

On 26 touko, 03:43, Marnen Laibow-Koser <rails-mailing-l…@andreas-
s.net> wrote:

Hmm. I’d say the best approach would be to keep display text out of
your JS files – put it in partials.

Thanks Marnen for your reply. I don’t quite follow, how do you
actually achieve this? I mean, there are plenty of UI libraries which
rely purely on js and those libraries are used via Javascript.
ActiveWidgets’ grid compent (ActiveWidgets | AW.UI.Grid)
is a good example. You set up your grid’s column names using library
API.

So basically you end up writing UI specific Javascript code. How these
translations could be separated as partials? Thanks for sharing your
thoughts.

Cheers!

hade wrote:

Hi,

I have quite many pure javascript files (*.js) in my rails project.
Unfortunately some of those files contain strings to be translated. I
have just started using I18n in rails. I’d like to hear your feedback
about how you are translating your javascript files.
[…]

Hmm. I’d say the best approach would be to keep display text out of
your JS files – put it in partials.

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]