Liveview problem with locale

Hi, i have a problem when change languaje with liveview, I see the change languaje for a second but reload and forget this

this is my router

scope "/", LanguajeWeb do
    pipe_through :browser

    # get "/", PageController, :index
    live "/", HomeLive, session: []
  end

and my home.ex

 def render(assigns) do
        LanguajeWeb.HomeLiveView.render("index.html", assigns)
end
def mount(_locale, socket) do
        {:ok, assign(socket, text: "Test")}
end

this is the home_live_view

defmodule LanguajeWeb.HomeLiveView do
    use LanguajeWeb, :view
    def render_sections(template, assigns) do
        render(LanguajeWeb.HomeView, template, assigns)
      end
end

my app.html.eex

<div class="flex w-full mt-5">
        <a href="?locale=es" class="ml-auto p-2">Español</a>
        <a href="?locale=en" class="p-2">English</a>
        <a href="?locale=ru" class="mr-auto p-2">Ruso</a>
      </div>
      <h3 class="w-full text-center text-xl  text-blue-700"><%= gettext "This tutorial jajaja is brought to you by %{company}",
  company: "PhraseApp" %></h3>
      <%= render @view_module, @view_template, assigns %>

in app.html.eex locale is work

and home/index.html.leex

<div class="w-full p-3 mt-16">
    <p class="ml-auto mr-auto text-center text-4xl">Traductor de santiago</p>
</div>
<div class="w-full inline-flex">
    <div class="w-10/12 inline-flex ml-auto mr-auto p-5">
        <div class="w-6/12 p-5">
            <div class="w-8/12 p-3 bg-white ml-auto rounded-lg h-48 overflow-y-scroll">
                <%= gettext "%{text}", text: @text %>
            </div>
        </div>
        <div class="w-6/12 p-5">
            <div class="w-8/12 p-3 bg-white mr-auto rounded-lg h-48 overflow-y-scroll">
            </div>
        </div>
    </div>
</div>

this is the example: https://github.com/ruben44bac/test_languaje

mix deps.get
mix ecto.create apps/languaje
cd apps/languaje_web/assets & npm install 
iex -S mix phx.server
1 Like

You need to add locale to the session in LanguajeWeb.Plugs.SetLocale.call/2:

conn |> put_session(:locale, locale) |> put_resp_cookie "locale", locale, max_age: 365*24*60*60

then in the router:

live "/", HomeLive, session: [:locale]

in finally in LanguajeWeb.HomeLive.mount/2:

Gettext.put_locale(locale)
6 Likes

I’m having the same problem, but somehow I cant figure out how to solve it…
I’m using https://hexdocs.pm/set_locale/api-reference.html
I added your lines of code to set_locale ex and to the router, but how can i access the locale in the liveview?

Update: Somehow with the modified set_locale plug the locale was always just nil. After changing to a self written plug everything works fine. Not sure why yet… :wink:

Hello,
I’m also using set_locale and get the same problem (also described here https://github.com/phoenixframework/phoenix_live_view/issues/815 )

So if I understand correctly you are using now a custom plug right?
Do you mind sharing your plug code?