Skip to content

template

Creates a template function that replaces placeholders in a string with values from a data object, supporting custom patterns and escaping.

Syntax

typescript
template(str: string, options?: TemplateOptions): (data: Record<string, any>) => string

TemplateOptions

PropertyTypeDescription
patternRegExp (optional)Custom pattern for placeholders (default: /\{\{(.*?)\}\}/g).
escape(value: string, key: string) => string (optional)Function to escape values before interpolation.

Parameters

ParameterTypeDescription
strstringThe string with placeholders in the format \{\{key\}\}.
optionsTemplateOptions (optional)Options for custom pattern and escaping.

Returns

TypeDescription
(data: Record<string, any>) => stringA function that takes a data object and returns the interpolated string.

Example

typescript
const fn = template("Hello, \{\{name\}\}!", { escape: (v) => v.toUpperCase() });
fn({ name: "Maria" }); // "Hello, MARIA!"

Notes

  • Throws TypeError if str is not a string, pattern is not a RegExp, or escape is not a function.
  • Placeholders without a corresponding value remain unchanged.
  • The backslashes () before the curly braces ( ) are escape characters used only to prevent conflicts with the documentation compiler. When using the function in practice, use simple braces without escaping.

References

Released under the MIT License.