Search documentation of Localize

# Localize.Substitution (Localize v0.39.0)

Copy Markdown View Source

Compiles substitution templates of the form `"{0} something {1}"` into token lists for efficient parameter substitution at runtime.

Templates are parsed once into a list of string literals and integer indices. At runtime, values are substituted for the integer indices to produce the final output.

## Summary

### Functions

parse(template)

Parses a substitution template into a list of tokens.

substitute(item, arg2)

Substitutes values into a pre-parsed template token list.

## Functions

# parse(template)

    @spec parse(String.t()) :: [String.t() | integer()]

Parses a substitution template into a list of tokens.

### Arguments

- `template` is a binary string that may include parameter markers like `{0}`, `{1}`, etc.

### Returns

- A list of tokens where substitution markers become integers and literal text remains as strings.

### Examples

    iex> Localize.Substitution.parse("{0}, {1}")
    [0, ", ", 1]

    iex> Localize.Substitution.parse("{0} something {1} else {2}")
    [0, " something ", 1, " else ", 2]

    iex> Localize.Substitution.parse("")
    []

# substitute(item, arg2)

    @spec substitute(term() | [term()], [String.t() | integer()]) :: [term()]

Substitutes values into a pre-parsed template token list.

### Arguments

- `values` is a value or list of values to substitute into the template.

- `tokens` is a template token list previously created by `parse/1`.

### Returns

- A list with values substituted for integer indices in the template.

### Examples

    iex> template = Localize.Substitution.parse("{0} and {1}")
    [0, " and ", 1]
    iex> Localize.Substitution.substitute(["a", "b"], template)
    ["a", " and ", "b"]

    iex> Localize.Substitution.substitute("x", [0, "!"])
    ["x", "!"]