hotwired/turbo-rails

How to Localize Error Messages?

Opened this issue · 1 comments

Hey,

I would like to localize the Content missing message from here:

this.element.innerHTML = `<strong class="turbo-frame-error">Content missing</strong>`;

but I am not sure what's the appropriate way since this is a JS file that's putting a hardcoded string.

How can I get this to work with I18n?

Would monkeypatching this to use I18n.t and using the extension .js.erb work?

@obahareth the "Content missing" message is presented after a turbo:frame-missing event is dispatched.

At the moment, there isn't a way to customize or localize the error message. If you need to adjust the message (or do something else), you can define a global event listener:

addEventListener("turbo:frame-missing", (event) => {
  event.preventDefault()

  event.target.innerHTML = `<strong class="turbo-frame-error">A localized Content missing message</strong>`
})

That event listener could be paired with a server-rendered <template> element elsewhere in the page:

<script>
  addEventListener("turbo:frame-missing", (event) => {
    const template = document.getElementById("turbo_frame_missing_template")

    event.preventDefault()

    event.target.replaceChildren(template.content.cloneNode(true))
  })
</script>

<body>
  <template id="turbo_frame_missing_template">
    <strong class="turbo-frame-error"><%= translate("turbo_frame_missing_message") %></strong>
  </template>

  <!-- ... -->
</body>