I'm trying to implement JS localization in Rails 7 app using i18n-js gem. I have some little script for validating contact form attachments and want to translate errors from that JS script. I already have 'rails-i18n' gem and it is working ok, but implementing i18n-js is driving me crazy. The documentation for this gem is confusing and all guides which I've found online or outdated, or have different approach and all have different syntax.
Is there any recent guide how to do this and what syntax I should use in JS scripts for translation? Thanks!
config/i18n-js.yml
translations:
- file: 'app/javascript/bundles/i18n/cs.js'
prefix: "import I18n from 'i18n-js';\n"
pretty_print: true
only: 'cs.*'
- file: 'app/javascript/bundles/i18n/ru.js'
prefix: "import I18n from 'i18n-js';\n"
pretty_print: true
only: 'ru.*'
app/javascript/application.js
import "@hotwired/turbo-rails"
import "./controllers"
import I18n from 'i18n-js'
window.I18n = I18n
application.html.haml
:javascript
var language = "<%= I18n.locale %>";
I18n.translations = <%== I18n::JS.filtered_translations.to_json %>;
config/locales/cs.yml
# javascript form errors
javascript:
too_many: Příliš mnoho souborů
javascript:
const errors = {
tooMany: I18n.t('too_many'),
update: It is working with following code in application.html.haml:
= javascript_tag do
window.I18n = #{t('javascript').to_json.html_safe}
and with this syntax in js:
const errors = {
tooMany: I18n.too_many,
but! when I'm switching locales and trying to fill-in the form again - it does not show any errors, I must reload page manually.
How you may go about implementing localization definitely comes with its own personal (or team) preferences.
Here's a mobile crypto wallet and how they register the i18n language dictionaries, and a link to how it is used. Register i18n and How to use
This syntax should seem familiar from the package docs