Idiom (idiom v0.1.1)

Summary

Types

Link to this type

translate_opts()

@type translate_opts() :: [to: String.t(), fallback: String.t() | [String.t()]]

Functions

Link to this function

child_spec(options)

See Idiom.Supervisor.child_spec/1.

Link to this function

t(key, opts \\ [])

Alias for translate/2

Link to this function

translate(key, opts \\ [])

@spec translate(String.t(), translate_opts()) :: String.t()

Translates a key into a target language.

The translate/2 function takes two arguments:

  • key: The specific key for which the translation is required.
  • opts: An optional list of options.

Target and fallback languages

For both target and fallback languages, the selected options are based on the following order of priority:

  1. The :to and :fallback keys in opts.
  2. The :lang and :fallback keys in the current process dictionary.
  3. The application configuration's :default_lang and :default_fallback keys.

The language needs to be a single string, whereas the fallback can both be a single string or a list of strings.

Namespaces

Keys can be namespaced.

Configuration

Application-wide configuration can be set in config.exs like so:

config :idiom,
  default_lang: "en",
  default_fallback: "fr"
  # default_fallback: ["fr", "es"]

Examples

iex> translate("hello", to: "es")
"hola"

# If no `:to` option is provided, it will check the process dictionary:
iex> Process.put(:lang, "fr")
iex> translate("hello")
"bonjour"

# If neither `:to` option is provided nor `:lang` is set in the process, it will check the application configuration:
# Given `config :idiom, default_lang: "en"` is set in the `config.exs` file:
iex> translate("hello")
"hello"

# If a key does not exist in the target language, it will use the `:fallback` option:
iex> translate("hello", to: "de", fallback: "fr")
"bonjour"

# If a key does not exist in the target language or the first fallback language:
iex> translate("hello", to: "de", fallback: ["pl", "fr"])
"bonjour"