Skip to main content

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.

note

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.'

Generate SEO meta tags from page data​

Build dynamic meta titles and descriptions from page data. Essential for SSR apps and static site generators optimizing for search engines.

const metaTitle = template("{siteName} | {pageTitle}", {
siteName: "My Store",
pageTitle: "Running Shoes",
});
// => "My Store | Running Shoes"

const metaDescription = template(
"Buy {productName} at {price}. {category} with free shipping on orders over {freeShippingMin}.",
{ productName: "Nike Air Max", price: "$129", category: "Running Shoes", freeShippingMin: "$75" }
);

Build notification messages for multiple channels​

Generate notification text for push, SMS, and in-app from a single template. Perfect for multi-channel notification systems.

const templates = {
push: "{userName}, your order #{orderId} is {status}!",
sms: "Order #{orderId} {status}. Track: {trackingUrl}",
inApp: "Your order #{orderId} has been {status}. Check details.",
};

const data = { userName: "Alice", orderId: "4521", status: "shipped", trackingUrl: "https://track.co/4521" };

const pushMsg = template(templates.push, data);
const smsMsg = template(templates.sms, data);
const inAppMsg = template(templates.inApp, data);