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}
Resolveskey
(or dot-notation path) indata
, then indefaults
. -
{key[index]}
Supports array indexing via[number]
on any path segment. -
{mapKey}
whendata.mapKey
is a Map Resolves viaMap.has(key)
andMap.get(key)
. -
{key ?? fallback}
or{key || fallback}
If the primary lookup yieldsundefined
ornull
(or for||
, alsofalse
,0
,''
), resolvesfallback
instead (first indata
, thendefaults
). -
{key:options}
or{nested.key:options}
Anything after the first:
is passed as theoptions
string to your hook.
Generic type parameters:
Type Parameters
Section titled “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
).
Parameters
Section titled “Parameters”template
Section titled “template”string
A string containing {…}
tokens to be replaced.
T
Primary lookup source. Can contain nested objects, arrays, or Maps.
defaults
Section titled “defaults”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:
- The resolved
key
string (after default-resolution), - The raw or defaulted
value
, - The parsed
options
string. If a hook returns non-null
/undefined
, that value is used as the replacement.
stringify
Section titled “stringify”(value
) => unknown
The objects are serialized using the stringify callback.
Returns
Section titled “Returns”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.
Example
Section titled “Example”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"