Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

Internationalization of javascript strings in a Rails application

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.

question from:https://stackoverflow.com/questions/65906295/internationalization-of-javascript-strings-in-a-rails-application

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...