Stimulus Discourse

I18n in Stimulus


#1

I need to add basic support for localizing a few strings in Stimulus.
Thus, I’d like to know how you guys have managed it before going down the road.

I’m currently looking at

Thank you.


#2

Try this:

# config/locales/en.yml
en:
  javascript:
    hello: Hello World!
# app/views/layouts/application.html.erb
...
<%= javascript_tag do %>
  window.I18n = <%= t("javascript").to_json.html_safe %>
<% end %>
...
// app/javascript/controllers/hello_controller.js
import { Controller } from "stimulus"

export default class extends Controller {
  static targets = [ "output" ]

  connect() {
    this.outputTarget.textContent = I18n.hello
  }
}

It’s pretty simple and it works great. The .html_safe part might look scary, but you should be good as long as you are in control of all translations.

Other option is to use gon to pass variables from Rails to JavaScript.


#3

Thanks for your reply.
I’m trying to keep the client-side separate from the server-side and, since I’m not expecting to translate a ton of strings I have added the following (I’m sure it can be written in a better way).

#my_controller.js
import { Controller } from "stimulus"
import  i18n          from "../modules/i18n"

export default class extends Controller {
...
el.innerHTML = i18n.t('hello')
...
}


#i18n.js
import locales from "../config/locales"

export default {
  t(keys) {
    const current = document.querySelector("body").getAttribute("data-locale")
    return keys.split('.').reduce((translation_hash, value) => translation_hash[value], locales[current])
  }
}

#locales.js
export default {
  en: {
      hello: 'hello'
  }
}

Hope this may be helpful to someone else.


#4

I’m sorry. That’s my bad that I made an assumption about your setup when you didn’t even mention Rails in your original post. I can’t help you in this case, but it looks that you already solved it :+1:.