ruby-on-railslocalizationrails-i18nstimulusjs

How to localize Stimulus JS value using i18n?


I am working on rails 6 application where I'm trying to store all displayed strings in locales files. I have a Stimulus controller named countdown_controller.js:

import { Controller } from "@hotwired/stimulus";

export default class extends Controller {

  static values = {
    message: { type: String, default: "Deal closed!" }
  }
}

en.yml:

en:
 deals:
   status:
     closed: "Deal closed!"

I want to use I18n.t("deals.status.closed") as a value for messageValue in countdown_controller.js instead of directly writing the string. I am not sure how to do that.


Solution

  • Simply converting countdown_controller.js to countdown_controller.js.erb worked for me. Then I used interpolation to inject the I18n.t("deals.status.closed") as follows:

    import { Controller } from "@hotwired/stimulus";
    
    export default class extends Controller {
    
      static values = {
        message: { type: String, default: "<%= I18n.t('deals.status.closed') %>" }
      }
    }
    

    P.S. I was getting an error initially as I changed the comment to use ruby syntax which begins with # instead of JS syntax which begins with //.