Hi Jacopo, Merry Christmas!
I created a gist out of some code I wrote for managing a multi-locale Phoenix LiveView project:
README.md
# Phoenix LiveView Multiple Locales
This gist was extracted from a Phoenix LiveView project where I needed to support multiple languages.
Translations are managed using GetText and the standard commands available in projects generated with Phoenix 1.7.
The code in this gist demonstrates how to use a Plug to store the locale in the session and a LiveView on_mount hook to set the current locale in LiveView assigns.
The Plug integrates with the rest of the project through a router pipeline, and the on_mount hook is attached to every LiveView by updating the generated `...Web` module.
lib-hello_web-components-layouts-root.html.heex
<!DOCTYPE html>
<html lang={@locale |> String.replace("_", "-")}>
<!-- ... -->
<.link
:for={
{locale, description, language} <- [
{"pt_BR", "Mudar idioma para", "Português"},
{"en", "Change language to", "English"},
{"de_AT", "Sprache ändern zu", "Deutsch"}
]
This file has been truncated. show original
lib-hello_web-plugs-set_locale.ex
defmodule HelloWeb.Plugs.SetLocale do
@moduledoc """
This plug is responsible for setting the locale in the session based on the
`lang` query parameter, existing session locale or `accept-language` HTTP
header.
## Behavior
- If the `lang` query parameter is present, it overwrites any existing locale
in the session and updates the session with the new locale.
This file has been truncated. show original
There are more than three files. show original
If memory serves me well, we cannot change the session from LiveView (see also a recent post Any way to store auth details in cookies using phoenix liveview - #2 by josevalim ).
The solution I use in the gist involves updating the session via Plug, and reading/sharing the locale between Plug (available in controllers) and LiveView using a global on_mount hook.
Hope that helps!