Parses the accept-language
header and sets the key
:plug_preferred_locales
of %Plug.Conn{}
to a list of preferred locales.
Documentation is available at HexDocs:
https://hexdocs.pm/plug_preferred_locales
If you use the Gettext package you can add something like this to your router pipeline:
defmodule MyappWeb.Router do
use MyappWeb, :router
pipeline :browser do
# ....
plug(PlugPreferredLocales, ignore_area: true)
plug(:set_language)
end
def set_language(conn, _opts) do
preferred_languages = MapSet.new(conn.private.plug_preferred_locales)
available_languages =
MyappWeb.Gettext
|> Gettext.known_locales()
|> MapSet.new()
intersection = MapSet.intersection(preferred_languages, available_languages)
if MapSet.size(intersection) > 0 do
intersection
|> MapSet.to_list()
|> List.first()
|> Gettext.put_locale()
end
conn
end
end
If available in Hex, the package can be installed
by adding plug_gettext
to your list of dependencies in mix.exs
:
def deps do
[
{:plug_preferred_locales, "~> 0.1.0"}
]
end