After a lot of reading and some experimentation I was able to pass my “locale” value from the Plug connection to my Liveview. The problem is that I though I was understanding how everything worked, but realised I’m not yet there as when trying different approaches I couldn’t and I still have an issue I don’t understand in my actual working code.
I believe it would be very helpful to everyone like me to clearly understand this picture. So I would first present my current approach that is working, point one issue and present alternative ways I though should work but don’t in hope someone could clarify the details.
As context, I have a Module Plug that properly injects a :locale value in the Conn assign(conn, :locale, "value").
A) Current working approach:
Router: live "/privpol", Priv_polLive, session: %{"locale" => @locale}
Liveview:
defmodule MyappWeb.Priv_polLive do
use MyappWeb, :live_view
@impl true
def mount(_params, %{"locale" => loc}, socket) do
IO.inspect loc
socket = assign_new(socket, :locale, fn -> loc end)
IO.inspect socket.assigns.locale
{:ok, socket }
end
end
Questions:
- In my console I can see a
niland alocalevalue on the same rendering. Why?
[debug] Processing with Phoenix.LiveView.Plug.Elixir.LiveappWeb.Priv_polLive/2
Parameters: %{}
Pipelines: [:browser]
nil
"en"
[info] Sent 200 in 2ms
- Visual Studio has a warning in my Router code saying:
undefined module attribute @locale...Makes sense as@localeshould only work in views and templates. but then why is it working?
B) Alternative 1: trying to pass the locale to the session in my Plug using put_session(conn, key, value). Seems very easy and as long as locale is in the session I was expecting it would be available in my 2nd mount in the Liveview inside socket. I tried to change the code in there and in my plug but couldn’t make this work. Maybe I’m missing some other configuration…
C) Alternative 2: trying to use the new get_connect_info(socket) in the Liveview mount, after reading the docs and adding my locale to the connect_info: in my endpoint:
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [:locale, session: @session_options]]
This brings an error at the endpoint side.
So, are all these 3 alternatives really alternatives or is there only 1 or 2 approaches that would work? Why?
What about the issues in my current working solution and how to tie it to the life cycle, mounting twice, specially the console nil followed by the "en"? What’s the proper way of passing the locale in the router to avoid warnings?
Thank you in advance.





















