Send emails i18n'd using backend-stored user language
[akkoma] / lib / pleroma / web / gettext.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.Gettext do
6 @moduledoc """
7 A module providing Internationalization with a gettext-based API.
8
9 By using [Gettext](https://hexdocs.pm/gettext),
10 your module gains a set of macros for translations, for example:
11
12 import Pleroma.Web.Gettext
13
14 # Simple translation
15 gettext "Here is the string to translate"
16
17 # Plural translation
18 ngettext "Here is the string to translate",
19 "Here are the strings to translate",
20 3
21
22 # Domain-based translation
23 dgettext "errors", "Here is the error message to translate"
24
25 See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
26 """
27 use Gettext, otp_app: :pleroma
28
29 def language_tag do
30 # Naive implementation: HTML lang attribute uses BCP 47, which
31 # uses - as a separator.
32 # https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang
33
34 Gettext.get_locale()
35 |> String.replace("_", "-", global: true)
36 end
37
38 def supports_locale?(locale) do
39 Pleroma.Web.Gettext
40 |> Gettext.known_locales()
41 |> Enum.member?(locale)
42 end
43
44 def locale_or_default(locale) do
45 if supports_locale?(locale) do
46 locale
47 else
48 Gettext.get_locale()
49 end
50 end
51
52 defmacro with_locale_or_default(locale, do: fun) do
53 quote do
54 Gettext.with_locale(Pleroma.Web.Gettext.locale_or_default(unquote(locale)), fn ->
55 unquote(fun)
56 end)
57 end
58 end
59 end