code_aks
code_aks

Reputation: 2074

How to use i18n-js with webpacker in rails 6?

I just switched to Rails 6 (6.0.0.rc1) which uses the Webpacker gem. I want to use i18n-js in some of my modules for translation purpose. How can configured i18n in my application with webpacker ?

Upvotes: 6

Views: 3941

Answers (3)

Vedran Mijatović
Vedran Mijatović

Reputation: 78

I wanted the locale of I18n JS module to be changed by setting the Rails I18n.locale in application controller (the standard Rails way of managing locale).

I managed it to work just by adding the gem "i18n-js" and running yarn add i18n-js. I tried to avoid bundle --binstubs and bin/rails webpacker:install:erb since i thought i wouldn't need it.

Added in app/javascript/packs/application.js:

// Import i18n-js and make I18n module available on views
import I18n from 'i18n-js'
window.I18n = I18n

Added before closing body in app/views/layouts/application.html.erb. Tried to put it in head but i'm using Turbolinks and it didn't work.

<script>
   I18n.locale = "<%= I18n.locale %>";
   I18n.translations = <%== I18n::JS.filtered_translations.to_json %>;
</script>

App running with:

  • rails '6.1.3'
  • ruby '2.7.2'
  • i18n-js '3.9.0'
  • yarn.lock says: i18n-js 3.8.0

Upvotes: 0

Malay
Malay

Reputation: 713

The right way is to follow this guide:

Gemfile

gem 'i18n-js'

bundle --binstubs
$ yarn add i18n-js
$ bin/rails webpacker:install:erb

app/javascript/i18n-js/index.js.erb

import I18n from "i18n-js"
I18n.translations = <%= I18n::JS.filtered_translations.to_json %>;
export default I18n

app/javascript/packs/application.js

import I18n from 'i18n-js/index.js.erb'
console.log(I18n.t('hello'))

Source: https://gist.github.com/bazzel/ecdff4718962e57c2d5569cf01d332fe

Upvotes: 1

code_aks
code_aks

Reputation: 2074

Sorry for the late answering but I have already resolved this issue as below :-

yarn add i18n-js

After this I have changed in below files

## javascript/packs/application.js

require("@rails/ujs").start()
require("@rails/activestorage").start()
require("channels")

window.jQuery = window.$ = require('jquery')

var Turbolinks = require("turbolinks");
Turbolinks.start();

import I18n from 'i18n-js'
window.I18n = I18n

And then to load all translations :-

## application.html.erb

<script>
   var language = "<%= I18n.locale %>";
   I18n.translations = <%== I18n::JS.filtered_translations.to_json %>;
</script>

Now translations are ready to use in js files:-

I18n.t('a.hello')

Upvotes: 4

Related Questions