Localize.Plug (Localize Web v0.6.0)

Copy Markdown View Source

Utility functions for setting the locale from the session for Localize and Gettext.

The primary use case is in LiveView on_mount callbacks where the locale needs to be restored from the session that was set during the initial HTTP request by Localize.Plug.PutLocale and Localize.Plug.PutSession.

Summary

Functions

Puts the locale from the session into the current process.

Functions

put_locale_from_session(session, options \\ [])

@spec put_locale_from_session(
  map(),
  keyword()
) :: {:ok, Localize.LanguageTag.t()} | {:error, {module(), String.t()}}

Puts the locale from the session into the current process.

Always sets the Localize process locale via Localize.put_locale/1. If Gettext backends are provided, the locale is also set on each backend.

This function is useful to place in the on_mount callback for a LiveView.

Arguments

  • session is any map, typically the map returned as part of the conn of a Phoenix or Plug request. A session is passed as the third parameter to the on_mount callback of a LiveView request.

  • options is a keyword list of options.

Options

  • :gettext is a Gettext backend module or a list of Gettext backend modules on which the locale will be set. The default is [] (no Gettext backends).

Returns

  • {:ok, locale} or

  • {:error, {exception, reason}}

Examples

iex> Localize.Plug.put_locale_from_session(session)
iex> Localize.Plug.put_locale_from_session(session, gettext: MyApp.Gettext)
iex> Localize.Plug.put_locale_from_session(session, gettext: [MyApp.Gettext, MyOtherApp.Gettext])

# In a LiveView
def on_mount(:default, _params, session, socket) do
  {:ok, locale} = Localize.Plug.put_locale_from_session(session, gettext: MyApp.Gettext)
  {:cont, socket}
end