Airbnb Polyglot.js

Public
Polyglot.js is a tiny I18n helper library developped by airbnb for translating your JS files
Icons/chart bar
Used 12 times
Created by
R Romain Manguin

Usage
Define the i18n keys you would like to use with polyglot and enjoy i18n in your JS files like Stimulus controllers and so on.

Gather a hash of phrases in your backend, and output them in a <script> tag at the bottom of the view:
<script>var polyglot = new Polyglot({phrases: #{raw phrases.to_json}});</script>

OR  define a helper
# app/helpers/application_helper.rb
def polyglot(phrases)
  "<script>var polyglot = new Polyglot({phrases: #{raw phrases.to_json}});</script>".html_safe
end

Call the helper at the bottom of the view and directly pass it the I18n keys you need in your JS files:
# app/views/**/*
= polyglot(I18n.t('javascript.greetings')


THEN enjoy i18n in your JS files:
# app/javascript/**/*
polyglot.t("hello")

official documentation: https://github.com/airbnb/polyglot.js/

Run this command in your Rails app directory in the terminal:

rails app:template LOCATION="https://railsbytes.com/script/zNPsEl"
Template Source

Review the code before running this template on your machine.

# install polyglot via yarn
run 'yarn add node-polyglot'

inject_into_file "app/javascript/packs/application.js" do <<~EOF
  import Polyglot from  "node-polyglot"
  window.Polyglot = Polyglot
  EOF
end

run "mkdir config/locales/javascript"

run "touch config/locales/javascript/en.yml"

inject_into_file "config/locales/javascript/en.yml" do <<~EOF
  # Put your javascript i18n keys here
  en:
    javascript:
  EOF
end

puts "Polyglot is here: Enjoy!, Profitez!, ¡Disfruta! 👅"
Comments

Sign up or Login to leave a comment.