I understand I can just use the /:locale path in router to get the locale and put_locale to set it. But that also means I’ve got to add Gettext.get_locale to every single link in the app, which is noise. Better would be to save it into session or use live_session.
Anyway seems like this should be a solved problem. What’s your go-to solution? I checked all the packages I could find, they just don’t support LiveView it seems.
You could utilize hooks in this case to avoid calling it explicitly for each mount.
# on_mount_hooks.ex
def on_mount(:set_locale, %{"locale" => locale} = _params, _session, socket)
when is_binary(locale) do
Gettext.put_locale(locale)
{:cont, socket}
end
def on_mount(:set_locale, _params, %{"locale" => locale} = _session, socket)
when is_binary(locale) do
Gettext.put_locale(locale)
{:cont, socket}
end
def on_mount(:set_locale, _params, _session, socket) do
{:cont, socket}
end
# example_web.ex
def live_view() do
quote do
on_mount({ExampleWeb.Live.OnMountHooks, :set_locale})
...
end
end