hotwired / turbo-rails

Use Turbo in your Ruby on Rails app
https://turbo.hotwired.dev
MIT License
2.13k stars 329 forks source link

How to Localize Error Messages? #686

Open obahareth opened 2 months ago

obahareth commented 2 months ago

Hey,

I would like to localize the Content missing message from here: https://github.com/hotwired/turbo-rails/blob/1aa7ba9d38dee1e1b4078a74404131122b907176/app/assets/javascripts/turbo.js#L1335

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?

seanpdoyle commented 2 months ago

@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>