1

I have a rails application, which has some strings inside the assets / javascripts files, how can I internationalize these strings? Note: I can't use the rails I18n, because I can't add the .erb extension to these javascript files, so I can't use ruby ​​code on them.

0

2 Answers 2

1

One way of doing this would be to write a simple rails task that generates a JavaScript file containing translations.

namespace :translations do
  desc "Create a JavaScript File containing translations"
  task :generate => :environment do
    locale = ARGV[1] || I18n.default_locale
    keys = ['hello', 'goodbye'] # ...
    I18n.with_locale(locale) do
      data = Hash[keys, keys.map { |k| I18n.t!(k) }]
    end
    begin
      f = File.open(Rails.root.join('app/assets/javascript/translations.js') , 'w')
      f.write("export default #{data.to_json}")
    ensure
      f.close
    end
  end
end

This would create an ES6 module that looks like this:

export default {
  hello: 'Ola',
  goodbye: 'Tchau'
}

Which you then import where you need it:

import Translations from 'translations';

If you're not using Webpack you could use the same approach with Sprockets but it don't really see the point as it will process ERB files which is a much simpler solution. You could also potentially use the ERB loader for Webpack to do this.

Sign up to request clarification or add additional context in comments.

10 Comments

Yes. developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules. If you dont want to use ES6 modules you could use something else like a global.
And its just a simple object so you just do Translations["hello"].
Also i need to have one file each language, it can't be a single file for all.
Rails.root.join('app/assets/javascript/', "translations-#{locale].js"). locale is here is the first argument to the rake task for example rake translations:generate fr. And then you would do import French from 'translations-fr';
this is what happens when I run rake command: I18n::MissingTranslationData: translation missing: pt-BR.hello
|
0

There is a gem i18n-js for doing this. You can add your strings to one of the translation yml files and access them in the exact same way as you do on the Rails side.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.