Skip to content

formatTemplate

formatTemplate<T, K>(template, data, defaults, hooks, stringify): string

Formats a template string by replacing {…} placeholders with values from the provided data object, supports nested paths, arrays, Maps, fallbacks, defaults, and custom hooks with inline options.

Placeholder syntaxes:

  • {key} or {nested.key.path} Resolves key (or dot-notation path) in data, then in defaults.

  • {key[index]} Supports array indexing via [number] on any path segment.

  • {mapKey} when data.mapKey is a Map Resolves via Map.has(key) and Map.get(key).

  • {key ?? fallback} or {key || fallback} If the primary lookup yields undefined or null (or for ||, also false,0,''), resolves fallback instead (first in data, then defaults).

  • {key:options} or {nested.key:options} Anything after the first : is passed as the options string to your hook.

Generic type parameters:

T extends Record<string, unknown> = Record<string, unknown>

Type of the main data object (keys and nested structures).

K extends Record<string, unknown> = T

Type of the defaults object (should mirror or extend T).

string

A string containing {…} tokens to be replaced.

T

Primary lookup source. Can contain nested objects, arrays, or Maps.

Partial<K> = {}

Secondary lookup source for missing or undefined keys in data.

TemplateHooks<T, K> = {}

Optional map of hook functions:

  • Specific hooks: properties named exactly by any valid path (e.g. "user.name", "items[2].price"), signature: (key: string, value: unknown, options: string) => any
  • Fallback hook: the '*' key, invoked when no specific hook matches. Hooks receive:
  1. The resolved key string (after default-resolution),
  2. The raw or defaulted value,
  3. The parsed options string. If a hook returns non-null/undefined, that value is used as the replacement.

(value) => unknown

The objects are serialized using the stringify callback.

string

The formatted result where each placeholder is replaced by:

  • The hook return value (if provided and non-null),
  • Otherwise String(value) of the resolved data/default,
  • Or left verbatim as {…} if no key was found.
const tpl = "User: {user.name}, 2nd Tag: {tags[1] ?? 'n/a'}, Color: {theme:red}";
const data = {
user: { name: "Alice" },
tags: ["admin", "editor"],
theme: "blue"
};
const defaults = {};
const hooks = {
"theme": (_k, v, opts) => opts === "red" ? "FF0000" : v
};
formatTemplate(tpl, data, defaults, hooks);
// → "User: Alice, 2nd Tag: editor, Color: FF0000"