Locale plug do not set language to LiveView page

Greetings! I have a simple plug to set locale:

  def call(conn, _opts) do
    case locale_from_params(conn) || locale_from_session(conn) || locale_from_header(conn) do
      nil     -> conn
      locale  ->
        conn = conn |> persist_locale_session(locale)
        IO.inspect conn

It works as intended with phoenix pages, but when it comes to LiveView pages - it does not work (by that I mean that default language is used). So to mention I see on page load desired locale, but when page is loaded, default locale is in charge again.

I solved it adding to live page`s mount function:

    Gettext.put_locale(Map.get(session, "locale"))

But it do not sees like a good idea to insert this line to every live page in the whole project.
P.S. There is a similar topic (How to handle localisation in live view? - #11 by idi527), is it still impossible to loss that mount line?

1 Like

For better code organization, you can try to use the on_mount/1 (doc) callback to put everything in one file.

1 Like

Why the locale is ‘lost’:

How to set is without putting a function in every mount:Phoenix.LiveView.Router — Phoenix LiveView v0.17.7 and the already mentioned Phoenix.LiveView — Phoenix LiveView v0.17.7

1 Like