Suggestions on determining current Rails locale in Stimulus controller?

I’m trying to find a convenient way to determine the current locale of a Rails application within the context of a stimulus controller. So far I’ve just added the 2 character locale code in a data attribute on a target within the controller, but I feel like there should be a better solution.

Anyone have any opinions here?

If there are going to be multiple instances of this controller (or multiple controllers that need the locale) I’d propose putting the locale into a meta tag in the head of the document. The upside of this, is that you wouldn’t need to pass it down through data attributes on every instance where you need it.

<head>
  <meta name="rails-locale" content="EN">
</head>
var locale = document.querySelector("meta[name='rails-locale']").content
2 Likes