Manage translations embedded into translation structs.
Although it can be used with any struct Localize.Translate shines when paired with an
Ecto.Schema. It allows you to keep the translations into a field of the schema and avoids
requiring extra tables for translation storage and complex joins when retrieving translations
from the database.
The runtime API lives on Localize.Translate itself:
translate/1,translate/2return a translated copy of an entire struct, or a single field when the second argument is a field name.translate/3andtranslate!/3return a single translated field with an explicit locale or locale fallback chain.translatable?/2reports whether a field is declared as translatable.locale_id/1validates a locale and returns the CLDR locale id translations are keyed by.default_locale/1resolves the locale of a struct's base fields, andlocale_chain/2expands a locale into the CLDR fallback chain the reads walk, for code that builds its own lookups, such as a data-layer calculation.
For Ecto.Query support, Localize.Translate.QueryBuilder provides the translated/4
and translated_as/4 macros (requires Ecto.SQL).
Locale handling
Localize.Translate builds on :localize for
CLDR-aware locale handling. Three properties follow:
All locale inputs validate. Atoms (
:en), strings ("en"), and%Localize.LanguageTag{}structs are accepted anywhere a locale is expected — in:locales,translate/N, andQueryBuilder.translated/4. Each value is run throughLocalize.validate_locale/1and unwrapped to its:cldr_locale_idatom. An invalid locale never raises at runtime:translate/2,3andQueryBuilder.translated/4leave it out of the fallback chain, so it resolves to the next locale or the base value, and onlytranslate!/3raises it. An invalid locale in the:localesoption raises when the schema compiles.Fallbacks walk the CLDR parent chain. A locale expands into a fallback chain by walking parents (e.g.
:"en-AU"→:"en-001"→:en, stopping before the:undroot). ForQueryBuilder, the chain is filtered to the locales declared in:localesso unsupported parents don't generate dead branches.The current locale is
Localize.get_locale/0.translate/1andtranslate/2(with a field name) default the locale fromLocalize.get_locale/0and walk its parents.
Mixed :locales lists like [:en, %Localize.LanguageTag{cldr_locale_id: :fr}] are
supported. After validation each entry is reduced to an atom, deduplicated, and
sorted.
When used, Localize.Translate accepts the following options:
:translates(required) - list of the fields that will be translated.:locales(optional) - the list of locales for which translations will be stored. Required if you use thetranslations/1macro to auto-generate the embedded schema. Locales are atoms (for example:en,:"en-AU").:default_locale(optional) - declares the locale of the base untranslated columns. The fields in the main schema are considered to be in this locale, and no separate translation embed is generated for it. Either a locale, or a{module, function, arguments}tuple for a default known only at runtime, such as the language of the site a record belongs to. The function is called asapply(module, function, [subject | arguments])with the struct being translated, ornilfor a query, and returns a locale ornil. Seedefault_locale/1. With a function, every locale in:localesgets an embed, so keep the default locale's text in the base fields, not in the container.:container(optional) - the name of the field that holds the translations. Defaults to:translations.
Structured translations
Structured translations are the preferred and recommended way of using Localize.Translate. To
use structured translations, use the translations/1 macro when defining a schema. The
translations/1 macro will define an embedded schema with the name being the parameter passed
to the translations/1 macro. Within the :translations field that is generated, an
embeds_one/2 call is added for each non-default locale in :locales. Here's an example
schema configuration:
defmodule MyApp.Article do
use Ecto.Schema
use Localize.Translate,
translates: [:title, :body],
locales: [:en, :es, :fr],
default_locale: :en
schema "articles" do
field :title, :string
field :body, :string
translations :translations
end
endWhen expanded by the Elixir compiler, the example above will look like the following code. It
is provided here only as an example to show what the translations/1 macro compiles to.
defmodule MyApp.Article do
use Ecto.Schema
schema "articles" do
field :title, :string
field :body, :string
embeds_one :translations, Translations, on_replace: :update, primary_key: false do
embeds_one :es, MyApp.Article.Translations.Fields
embeds_one :fr, MyApp.Article.Translations.Fields
end
end
end
defmodule MyApp.Article.Translations.Fields do
use Ecto.Schema
@primary_key false
embedded_schema do
field :title, :string
field :body, :string
end
endReflection
Any module that uses Localize.Translate will have an autogenerated __trans__ function that
can be used for runtime introspection of the translation metadata. Code that builds a
translatable module some other way, such as a framework extension, generates it with
reflection/1.
__trans__(:fields)- Returns the list of translatable fields.__trans__(:container)- Returns the name of the translation container.__trans__(:locales)- Returns the configured locales (ornilif not given).__trans__(:default_locale)- Returns the:default_localeoption as given: a locale, a{module, function, arguments}tuple, ornil.default_locale/1resolves it. The fields in the main schema are considered to be in this locale.__trans__(:associations)- Returns the fields that hold related records, whichtranslate/2translates too. For an Ecto schema these are its associations and embeds. A module that defines__trans__/1itself, such as one built by a data layer other than Ecto, answers with its own list.
Summary
Types
A struct field as an atom.
A locale identifier as an atom (for example :en, :"en-AU") or a string.
When translating or querying either a single locale or a list of locales can be provided.
A translatable struct that uses Localize.Translate.
Functions
Returns the default locale of a translatable struct or module: the locale its base fields are written in.
Expands a locale, or a list of locales, into the CLDR fallback chain that
translate/2,3 and QueryBuilder.translated/4 walk.
Validates a locale and returns its canonical CLDR locale id, the key translations are stored and read under.
Defines the __trans__/1 reflection that makes a module translatable.
Checks whether the given field is translatable or not.
Translates a whole struct into the current locale.
Translates a whole struct (or a single field) into the given locale.
Translates a single field into the given locale.
Translates a single field into the given locale, raising if no translation is available.
Defines the embedded translation container field on an Ecto.Schema.
Defines the embedded translation container field with explicit locales.
Validates the translations a changeset leaves on its record, for an Ecto schema whose base fields are in its default locale.
Types
@type field() :: atom()
A struct field as an atom.
A locale identifier as an atom (for example :en, :"en-AU") or a string.
When translating or querying either a single locale or a list of locales can be provided.
A list of locales acts as a fallback chain: each locale is tried in order until a translation is found.
@type translatable() :: struct()
A translatable struct that uses Localize.Translate.
Functions
@spec default_locale(translatable() | module() | term()) :: atom() | nil
Returns the default locale of a translatable struct or module: the locale its base fields are written in.
The schema's :default_locale option is either a locale or a {module, function, arguments} tuple. A tuple is called as apply(module, function, [subject | arguments]),
where the subject is the struct, or nil when a module is given, as it is for a query.
Arguments
translatableis a struct that usesLocalize.Translate, or a module that does.
Returns
The default locale as a CLDR locale id atom, such as
:enor:"fr-CA", ornilwhen the schema has no default locale, or its function returnsnilor a value that is not a valid locale, or whentranslatableis not a struct or module that usesLocalize.Translate. With no default locale every locale is looked up in the translation container, so the base fields must not also have an entry there.
Examples
iex> Localize.Translate.default_locale(%Localize.Translate.Comment{})
:en
iex> Localize.Translate.default_locale(Localize.Translate.Comment)
:en
@spec locale_chain(locale_list() | struct() | nil, keyword()) :: [atom()]
Expands a locale, or a list of locales, into the CLDR fallback chain that
translate/2,3 and QueryBuilder.translated/4 walk.
Each locale is validated and followed up its CLDR parent chain, stopping before the root
(:"en-AU" → :"en-001" → :en). A list is expanded locale by locale and
deduplicated in order. A locale that is not valid, nil included, or that resolves to
the CLDR root und is left out, as the reads leave it out, so a locale taken from a
request is safe to pass.
Arguments
locale_or_localesis a locale (an atom, a string or aLocalize.LanguageTag) or a list of them.optionsis a keyword list of options.
Options
:supportedis a list of locale atoms to keep, such as a schema's__trans__(:locales), dropping parents no translation is stored for.nilor an empty list, the default, keeps the whole chain.:default_localeis the locale of the base fields, kept in the chain when:supportedfilters it even if it is not listed, so a read of it still reaches the base fields.translate/2,3andQueryBuilder.translated/4filter the same way.
Returns
- The chain as a list of CLDR locale id atoms, which is empty when no locale is valid.
Examples
iex> Localize.Translate.locale_chain("fr-CA")
[:"fr-CA", :fr]
iex> Localize.Translate.locale_chain([:"en-AU", :es])
[:"en-AU", :"en-001", :en, :es]
iex> Localize.Translate.locale_chain(["not a locale", :es])
[:es]
iex> Localize.Translate.locale_chain(:"en-AU", supported: [:en, :es])
[:en]
iex> Localize.Translate.locale_chain([:en, :es], supported: [:es, :fr], default_locale: :en)
[:en, :es]
@spec locale_id(locale() | Localize.LanguageTag.t() | nil) :: {:ok, atom()} | {:error, Exception.t()}
Validates a locale and returns its canonical CLDR locale id, the key translations are stored and read under.
Atoms, strings and Localize.LanguageTag structs are accepted, and converge to the
same id: "fr_CA", :"fr-CA" and "fr-CA" are all :"fr-CA". A language's default
region is folded into the language, as CLDR keeps no data of its own for it, so
"en-US" is :en.
Arguments
localeis a locale: an atom, a string or aLocalize.LanguageTag.
Returns
{:ok, locale_id}with the CLDR locale id as an atom, or{:error, exception}whenlocaleis not a valid locale, isnilor empty, or is a language CLDR has no data for, which resolves to the rootund. Every such language would share that one key, so none is accepted.
Examples
iex> Localize.Translate.locale_id("fr_CA")
{:ok, :"fr-CA"}
iex> Localize.Translate.locale_id("en-US")
{:ok, :en}
iex> {:error, %Localize.InvalidLocaleError{}} = Localize.Translate.locale_id("tlh")
iex> {:error, %Localize.InvalidLocaleError{}} = Localize.Translate.locale_id(nil)
Defines the __trans__/1 reflection that makes a module translatable.
use Localize.Translate calls this for you. Call it directly only from code that
builds a translatable module some other way, such as a framework extension, so the
module answers every key Localize.Translate asks for, including any a later
release adds.
Arguments
optionsis a keyword list of options.
Options
:fieldsis the list of translatable fields. Required.:containeris the field holding the translations. Defaults to:translations.:localesis the list of locale atoms translations may be stored for, ornilfor any. Defaults tonil.:default_localeis the locale of the base fields: a locale, a{module, function, arguments}tuple, ornil. Defaults tonil. Seedefault_locale/1.:storeis theLocalize.Translate.Storemodule. Defaults toLocalize.Translate.Store.Embedded.:store_optionsis the keyword list of options passed to the store. Defaults to[].:associationsis the list of fields holding related records thattranslate/2translates too, or:schemafor an Ecto schema's associations and embeds. Defaults to:schema, which is no fields for a module that is not an Ecto schema.
Returns
- The quoted definitions of
__trans__/1, answering:fields,:container,:locales,:default_locale,:store,:store_optionsand:associations. An option of the wrong shape raises anArgumentErrorwhen the module compiles.
Examples
defmodule MyApp.Note do
require Localize.Translate
defstruct text: nil, translations: %{}
Localize.Translate.reflection(fields: [:text], default_locale: :en)
end
@spec translatable?(module() | translatable(), String.t() | atom()) :: boolean()
Checks whether the given field is translatable or not.
A string field is compared with the declared field names as strings, so a field name taken from a request never creates an atom.
Arguments
module_or_translatableis either a module that usesLocalize.Translateor a struct of that module.fieldis the field name as an atom or string.
Returns
trueif the given field is translatable.falseif the given field is not translatable, if the module or struct does not useLocalize.Translate, or if either argument is not a module or a field name.
Examples
Assuming the Article schema defined in Structured translations.
iex> Localize.Translate.translatable?(Article, :title)
true
iex> Localize.Translate.translatable?(Article, "title")
true
iex> article = %Article{}
iex> Localize.Translate.translatable?(article, :not_existing)
false
iex> Localize.Translate.translatable?(Date, :day)
false
@spec translate(translatable()) :: translatable()
Translates a whole struct into the current locale.
Equivalent to translate(translatable, locale) with locale resolved from
Localize.get_locale/0 when the optional :localize dependency is loaded, falling back
to the schema's :default_locale otherwise.
Arguments
translatableis a struct that usesLocalize.Translate.
Returns
- The translated struct. A value that is not a struct using
Localize.Translateis returned unchanged.
Examples
iex> comment = %Localize.Translate.Comment{
...> comment: "Hello",
...> transcriptions: %{"fr" => %{"comment" => "Bonjour"}}
...> }
iex> Localize.put_locale(:fr)
iex> Localize.Translate.translate(comment).comment
"Bonjour"
@spec translate(translatable(), locale_list() | field() | struct()) :: translatable() | any()
Translates a whole struct (or a single field) into the given locale.
Returns the struct with every translatable field — and every translatable association or
embed — replaced by the value for the requested locale, falling back to the default
value when the locale has no entry. If the second argument is the name of a translatable
field, returns that single translated field using the current locale (see translate/3
for an explicit locale).
Arguments
translatableis a struct that usesLocalize.Translate.locale_or_fieldis one of:an atom or string locale (e.g.
:es,"fr"),a list of locales acting as a fallback chain,
a
%Localize.LanguageTag{}— when the optional:localizedependency is loaded, expanded into a fallback chain by walking the CLDR parent chain, oran atom field name — translates a single field using the current locale (see
translate/3).
Returns
- The translated struct, or the translated value of a single field. A locale that is
not valid is left out of the chain, so the struct is returned untranslated when no
valid locale is left. A field whose store returns
{:error, exception}keeps its base value. A value that is not a struct is returned unchanged.
Examples
# Translate the entire article into Spanish
Localize.Translate.translate(article, :es)
# Fallback chain — Deutsch missing, Spanish wins
Localize.Translate.translate(article, [:de, :es])
@spec translate(translatable(), field() | String.t(), locale_list() | struct()) :: any()
Translates a single field into the given locale.
Looks up the field's translation in the given locale (or first match in a fallback chain) and returns it. Returns the base value if no translation is available.
Arguments
translatableis a struct that usesLocalize.Translate.fieldis the name of the translatable field as an atom or a string.localeis either a single locale or a list of locales acting as a fallback chain.
Returns
The translated value, or the value from the base column when no translation exists for any locale in the chain. The chain is filtered to the schema's
:locales, with its default locale kept, asQueryBuilder.translated/4filters it, so a stored locale the schema does not list is not read. Aniltranslation counts as missing, so the chain moves on to its next locale. A locale that is not valid, includingnil, is left out of the chain rather than raised on, so a locale taken from a request is safe to pass. A store that returns{:error, exception}, one that could not answer, stops the chain and the base value is returned; usetranslate!/3to have that raised.The base value of a field that is not declared translatable, or
nilfor a field the struct does not have or a value that is not a struct. A string field name never creates an atom.
Examples
# Spanish title
Localize.Translate.translate(article, :title, :es)
# Unknown locale falls back to the base column
Localize.Translate.translate(article, :title, :de)
# Fallback chain
Localize.Translate.translate(article, :title, [:de, :es])
# A field that is not translatable is its base value
Localize.Translate.translate(article, :id, :es)
@spec translate!(translatable(), field() | String.t(), locale_list() | struct()) :: any()
Translates a single field into the given locale, raising if no translation is available.
Strict variant of translate/3. Where translate/3 falls back to the base value when a
translation is missing, translate!/3 raises so callers can distinguish "no
translation" from "translation equals the default".
Arguments
translatableis a struct that usesLocalize.Translate.fieldis the name of the translatable field as an atom or a string.localeis either a single locale or a list of locales acting as a fallback chain.
Returns
The translated value.
Raises a
RuntimeErrorif no translation exists for any locale in the chain. Aniltranslation counts as missing.Raises the store's exception if the store returns
{:error, exception}, one that could not answer, such as an unreachable translation service.Raises an
ArgumentErroriftranslatableis not a struct that usesLocalize.Translateorfieldis not one of its translatable fields.Raises a
Localize.InvalidLocaleErrorif any locale in the chain is not valid, includingnil.
Examples
Localize.Translate.translate!(article, :title, :de)
** (RuntimeError) translation doesn't exist for field ':title' in locale :de
Defines the embedded translation container field on an Ecto.Schema.
Within an Ecto.Schema block, expands into an embeds_one/3 declaration for the named
container field plus auto-generated Translations and Translations.Fields embedded
schemas — one embeds_one per non-default locale, each holding the translatable string
fields declared in :translates.
Arguments
field_nameis the name of the container field on the parent schema, given as an atom (commonly:translations).translation_module(optional) is the alias name of the generated translation schema. Defaults toTranslations. Pass an alias to use a different module name under the parent.locales_or_options(optional) is either an explicit list of locale atoms, or a keyword list of options. When omitted, the locales configured via the:localesoption onuse Localize.Translateare used.
Options
:build_field_schema— whentrue(the default), generates both the translation schema (Translations, or thetranslation_modulegiven) and its innerFieldsschema. Whenfalse, neither is generated: the container field still embeds the translation schema, so define it yourself with oneembeds_oneper non-default locale, pointing at aFieldsschema of your own, which may carry extra fields such as an update timestamp.:fields_module— a per-locale embedded schema of your own, used in place of the generatedFieldsschema. The translation schema is still generated, with each non-default locale embedding this module. It must be anEcto.Schemathat defines every field in:translatesas a:string, which is checked when the parent schema compiles, and it may define any other fields, such as an update timestamp or the name of the translator. It must be compiled before the parent schema, so it cannot be a module nested inside it. It cannot be combined withbuild_field_schema: false.
Any other option raises an ArgumentError when the schema compiles.
Returns
- The quoted
embeds_one/3declaration for the container field, together with the generated translation schema and, unless:fields_moduleorbuild_field_schema: falseis given, itsFieldsschema. One embed is generated per locale, leaving out a literal:default_locale; with a function default every locale gets one, since the default is known only at runtime.
Examples
defmodule MyApp.Article do
use Ecto.Schema
use Localize.Translate,
translates: [:title, :body],
locales: [:en, :es, :fr],
default_locale: :en
schema "articles" do
field :title, :string
field :body, :string
translations :translations
end
endA per-locale schema of your own keeps state beside each locale's translations:
defmodule MyApp.Article.TranslationFields do
use Ecto.Schema
@primary_key false
embedded_schema do
field :title, :string
field :body, :string
field :translated_by, :string
field :machine_translated, :boolean, default: false
end
end
defmodule MyApp.Article do
use Ecto.Schema
use Localize.Translate,
translates: [:title, :body],
locales: [:en, :es, :fr],
default_locale: :en
schema "articles" do
field :title, :string
field :body, :string
translations :translations, Translations, fields_module: MyApp.Article.TranslationFields
end
endLocalize.Translate.translate/3 and Localize.Translate.QueryBuilder read only the
fields in :translates. A query on a whole locale, translated(Article, a, :es), reads
the locale's whole object, so a locale that holds only such state is not NULL.
Defines the embedded translation container field with explicit locales.
Four-arity form of translations/3. Use this when you want to override the configured
:locales option for a single schema, or to pass an options keyword list alongside an
explicit locale list.
Arguments
field_nameis the name of the container field on the parent schema, as an atom.translation_moduleis the alias name of the generated translation schema.localesis the explicit list of locale atoms for which translation embeds are generated. A literal:default_localeis left out.optionsis a keyword list of options.
Options
:build_field_schemaand:fields_module, as described fortranslations/3.
Returns
- The quoted
embeds_one/3declaration for the container field and the generated schemas, as fortranslations/3, with one embed per locale inlocales.
Examples
defmodule MyApp.Article do
use Ecto.Schema
use Localize.Translate,
translates: [:title, :body],
locales: [:en, :es, :fr],
default_locale: :en
schema "articles" do
field :title, :string
field :body, :string
# Only Spanish translations for this schema, whatever :locales says
translations :translations, Translations, [:es], []
end
end
@spec validate_translations(Ecto.Changeset.t()) :: Ecto.Changeset.t()
Validates the translations a changeset leaves on its record, for an Ecto schema whose base fields are in its default locale.
The base fields hold the default locale's text, so the translation container must
not hold it too: if it did, a query and translate/3 could disagree about which to
read. With a literal :default_locale the generated translations/1 schema has no
embed for it, but a {module, function, arguments} default is known only per record,
so every locale gets an embed and only a validation can keep the default locale's
entry empty. Call this from a changeset function.
The check runs when the container or the record's default locale changes, so a row stored before the rule was enforced does not block unrelated updates.
Arguments
changesetis anEcto.Changesetfor a schema that usesLocalize.Translate.
Returns
- The changeset, with an error on the container field when the record's translations
hold text for its default locale, or, for a map container, for a locale that is not
valid or not in the schema's
:locales. A changeset for a schema that does not useLocalize.Translateis returned unchanged.
Examples
def changeset(article, params) do
article
|> cast(params, [:title, :body, :site_id])
|> cast_embed(:translations)
|> Localize.Translate.validate_translations()
end