DEV Community

loading...

Discussion on: I18n with Phoenix LiveView

Collapse
oliverandrich profile image
Oliver Andrich

If you do i18n, you also want to use l10n from my point of view. If you add Cldr for l10n, you can just add the plug from it.

plug(Cldr.Plug.SetLocale,
      apps: [cldr: Jocasta.Cldr, gettext: Jocasta.Gettext],
      from: [:accept_language]
    )
Enter fullscreen mode Exit fullscreen mode

And then you add another plug to push the locale to your session.

defmodule JocastaWeb.Plug.PutLocaleIntoSession do
  @moduledoc """
  Plug to store the current locale in the session.
  """

  import Plug.Conn

  def init(_opts), do: nil

  def call(conn, _opts) do
    %Cldr.LanguageTag{cldr_locale_name: locale} = conn.private.cldr_locale
    put_session(conn, "locale", locale)
  end
end
Enter fullscreen mode Exit fullscreen mode

And then you should add this code to your assert_defaults function for example.

def assign_locale(socket, %{"locale" => locale} = _session) do
    # Restore the locale based on the locale stored in the session.
    Cldr.put_locale(Jocasta.Cldr, locale)
    Gettext.put_locale(Jocasta.Gettext, locale)

    assign(socket, locale: locale)
  end
Enter fullscreen mode Exit fullscreen mode
Forem Open with the Forem app