template()
template(
template,data):string
Replaces {key} placeholders in a string with values from a data object.
๐ Why is this a Hidden Gem?
Lightweight string interpolation with support for nested paths ({user.name}). No regex complexity, no external dependencies.
Supports nested paths ({user.name}). Use {{ and }} for literal braces. Missing keys become empty strings.
Parametersโ
template: stringโ
The template string with {key} placeholders.
data: Record<string, unknown> = {}โ
The data object containing values.
Returns: stringโ
The interpolated string.
Sinceโ
2.0.0
Performanceโ
O(n ร m) time where n is template length, m is max path depth. Single regex pass with reduce for nested paths.
Also known asโ
template (Lodash, es-toolkit, Radashi, Antfu) ยท โ (Remeda, Ramda, Effect, Modern Dash)
Exampleโ
template('Hello {name}', { name: 'World' });
// => 'Hello World'
template('{user.name} <{user.email}>', {
user: { name: 'John', email: 'john@example.com' }
});
// => 'John <john@example.com>'
template('Literal: {{escaped}}', {});
// => 'Literal: {escaped}'
How it works?โ
Replaces {key} placeholders with values from a data object.
Supports nested paths.
Nested Pathsโ
Escape Bracesโ
Use {{ and }} for literal braces.
Missing Keysโ
Missing keys become empty strings.
Use Casesโ
Interpolate dynamic strings ๐โ
Replace placeholders in a string with data values. Perfect for localization (i18n) or generating dynamic messages.
const msg = template('Welcome, {user.name}!', { user: { name: 'Alice' } });
// 'Welcome, Alice!'
Render email notificationsโ
Build transactional email bodies from templates and user data. Avoids manual string concatenation and keeps templates readable.
const emailBody = template(
'Hi {name}, your order #{orderId} has been {status}. Track it at {trackingUrl}.',
{ name: 'Alice', orderId: '8842', status: 'shipped', trackingUrl: 'https://track.example.com/8842' }
);
// 'Hi Alice, your order #8842 has been shipped. Track it at https://track.example.com/8842.'
Format error messages with contextโ
Inject runtime context into error message templates for clearer debugging.
const errorTemplates = {
NOT_FOUND: 'Resource {resource} with id {id} not found.',
RATE_LIMIT: 'Rate limit exceeded for {endpoint}. Retry after {retryAfter}s.',
};
const msg = template(errorTemplates.NOT_FOUND, { resource: 'User', id: '42' });
// 'Resource User with id 42 not found.'