Internationalization of javascript strings in a Rails application

Viewed 193

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.

2 Answers

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.

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.

Related