Translation syntax

g18n translation data consists only of string keys and string values. It supports dotted keys, parameter placeholders, context keys, and flat or nested JSON.

Dotted keys

Dots organize strings for your webpage. There is no enforced hierarchy depth.

let translations =
  g18n.new_translations()
  |> g18n.add_translation("page.profile.title", "Profile")

let translator = g18n.new_translator(translations)
g18n.translate(translator, "page.profile.title")

Parameters

A placeholder is a name between { and }. Add matching values with new_format_params and add_param.

let translations =
  g18n.new_translations()
  |> g18n.add_translation("page.welcome", "Welcome {name}!")
let translator = g18n.new_translator(translations)
let params =
  g18n.new_format_params()
  |> g18n.add_param("name", "Alice")

g18n.translate_with_params(translator, "page.welcome", params)
// "Welcome Alice!"

A placeholder without a supplied parameter remains unchanged.

Context keys

Context is encoded with the exact key@context convention.

let translations =
  g18n.new_translations()
  |> g18n.add_translation("open", "Open")
  |> g18n.add_context_translation("open", "file", "Open file")
let translator = g18n.new_translator(translations)

g18n.translate_with_context(translator, "open", g18n.Context("file"))
// "Open file"

g18n.translate_with_context(translator, "open", g18n.NoContext)
// "Open"

translate_with_context_and_params combines context lookup with parameter interpolation.

Flat JSON

Flat JSON stores dotted keys directly:

{
  "page.title": "Welcome",
  "page.greeting": "Hello {name}!"
}
let assert Ok(translations) = g18n.translations_from_json(json_source)
let encoded = g18n.translations_to_json(translations)

Nested JSON

Nested objects are flattened into the same dotted keys:

{
  "page": {
    "title": "Welcome",
    "greeting": "Hello {name}!"
  }
}
let assert Ok(translations) =
  g18n.translations_from_nested_json(json_source)
let encoded = g18n.translations_to_nested_json(translations)
Search Document