Save user locale and use it to translate things

Signed-off-by: Thomas Citharel <tcit@tcit.fr>
This commit is contained in:
Thomas Citharel
2019-10-01 13:08:09 +02:00
parent d5a15b8a99
commit a84cfb5910
31 changed files with 155 additions and 157 deletions

View File

@@ -21,4 +21,27 @@ defmodule MobilizonWeb.Gettext do
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :mobilizon
def put_locale(locale) do
locale = determine_best_locale(locale)
Gettext.put_locale(MobilizonWeb.Gettext, locale)
end
@spec determine_best_locale(String.t()) :: String.t()
def determine_best_locale(locale) do
locale = String.trim(locale)
locales = Gettext.known_locales(MobilizonWeb.Gettext)
cond do
# Either it matches directly, eg: "en" => "en", "fr" => "fr", "fr_FR" => "fr_FR"
locale in locales -> locale
# Either the first part matches, "fr_CA" => "fr"
split_locale(locale) in locales -> split_locale(locale)
# Otherwise default to english
true -> "en"
end
end
# Keep only the first part of the locale
defp split_locale(locale), do: locale |> String.split("_", trim: true, parts: 2) |> hd
end