@bernierllc/email-template-engine
v1.0.2
Published
Email template processing engine with compilation, rendering, and text generation
Readme
@bernierllc/email-template-engine
Email template processing engine providing template compilation, variable substitution, base template composition, text version generation, and validation.
Installation
npm install @bernierllc/email-template-engineFeatures
- ✅ Handlebars Template Compilation - Compile and render templates with variable substitution
- ✅ Base Template Composition - Combine header, content, and footer into complete emails
- ✅ Variable Extraction - Automatically extract and analyze template variables
- ✅ Text Version Generation - Convert HTML to plain text for email clients
- ✅ Template Validation - Syntax checking and error detection
- ✅ Custom Helpers - Extend with custom Handlebars helpers
- ✅ TypeScript Support - Full type definitions included
- ✅ Zero Dependencies on @bernierllc - Pure core package
Usage
Basic Template Rendering
import { EmailTemplateEngine } from '@bernierllc/email-template-engine';
const engine = new EmailTemplateEngine();
// Simple variable substitution
const result = engine.render(
'<p>Hello {{name}}!</p>',
{ name: 'John' }
);
console.log(result.data); // '<p>Hello John!</p>'Building Complete Email Templates
import { buildEmailTemplate } from '@bernierllc/email-template-engine';
const result = await buildEmailTemplate(
{
headerHtml: '<html><body><header>Company Logo</header>',
footerHtml: '<footer>© 2025 Company</footer></body></html>',
},
'<h1>{{title}}</h1><p>{{message}}</p>',
{
title: 'Welcome',
message: 'Thank you for joining!',
}
);
console.log(result.data?.html); // Complete HTML email
console.log(result.data?.text); // Plain text versionVariable Extraction
import { extractTemplateVariables } from '@bernierllc/email-template-engine';
const template = '<h1>{{title}}</h1><p>{{user.name}}</p>';
const result = extractTemplateVariables(template);
console.log(result.data);
// [
// { name: 'title', path: 'title', type: 'string', occurrenceCount: 1, ... },
// { name: 'user', path: 'user.name', type: 'object', occurrenceCount: 1, ... }
// ]Template Validation
import { validateEmailTemplate } from '@bernierllc/email-template-engine';
const result = validateEmailTemplate('<p>{{name}}</p>');
if (!result.data?.isValid) {
console.error('Validation errors:', result.data?.errors);
}HTML to Text Conversion
import { generateTextFromHtml } from '@bernierllc/email-template-engine';
const result = generateTextFromHtml(
'<h1>Welcome</h1><p>Check out our <a href="https://example.com">website</a></p>'
);
console.log(result.data);
// WELCOME
//
// Check out our website [https://example.com]API Reference
EmailTemplateEngine
Main class for template processing.
Methods
compile(template: string, options?: CompilationOptions): TemplateResult<HandlebarsTemplateDelegate>
Compile a Handlebars template into a reusable function.
Options:
strict- Throw on undefined variables (default: false)noEscape- Disable HTML escaping (default: false)helpers- Custom Handlebars helperspartials- Template partials
render(template: string, data: Record<string, unknown>, options?: CompilationOptions): TemplateResult<string>
Compile and render template with data in one step.
buildCompleteTemplate(baseTemplate: BaseTemplate, content: string, variables?: Record<string, unknown>): Promise<TemplateResult<BuiltTemplate>>
Build complete email by combining header, content, and footer.
Returns:
html- Complete rendered HTMLtext- Plain text versionvariables- Extracted template variablesmetadata- Build metrics (time, variable count, content length)
generateTextVersion(html: string, options?: TextGenerationOptions): TemplateResult<string>
Convert HTML to plain text.
Options:
wordwrap- Wrap at N characters (default: 80)preserveNewlines- Keep line breaks (default: true)uppercaseHeadings- Uppercase headings (default: true)
extractVariables(template: string): TemplateResult<TemplateVariable[]>
Extract all variables from template.
validateTemplate(template: string): TemplateResult<TemplateValidationResult>
Validate template syntax and structure.
Convenience Functions
All methods are available as standalone functions:
import {
compileTemplate,
renderTemplate,
buildEmailTemplate,
generateTextFromHtml,
extractTemplateVariables,
validateEmailTemplate,
} from '@bernierllc/email-template-engine';Default Helpers
Built-in Handlebars helpers included:
formatDate- Format date objectsuppercase- Convert string to uppercaselowercase- Convert string to lowercase
const result = engine.render(
'<p>{{uppercase name}}</p>',
{ name: 'john' }
);
// <p>JOHN</p>Custom Helpers
Add your own Handlebars helpers:
const engine = new EmailTemplateEngine();
const result = engine.render(
'<p>Price: {{currency amount}}</p>',
{ amount: 99.5 },
{
helpers: {
currency: (value: number) => `$${value.toFixed(2)}`,
},
}
);
// <p>Price: $99.50</p>Error Handling
All methods return a TemplateResult<T> object:
const result = engine.render(template, data);
if (!result.success) {
console.error('Template error:', result.error);
return;
}
// Safe to use result.data
console.log(result.data);Examples
Welcome Email
const engine = new EmailTemplateEngine();
const welcomeTemplate = `
<h1>Welcome to {{companyName}}</h1>
<p>Hi {{userName}},</p>
<p>Your account email: {{email}}</p>
<a href="{{verificationLink}}">Verify Account</a>
`;
const result = await engine.buildCompleteTemplate(
{
headerHtml: '<html><body style="font-family: Arial;">',
footerHtml: '<footer>© 2025 Company</footer></body></html>',
},
welcomeTemplate,
{
companyName: 'ACME Corp',
userName: 'John Doe',
email: '[email protected]',
verificationLink: 'https://example.com/verify/abc123',
}
);Order Confirmation
const orderTemplate = `
<h1>Order Confirmation</h1>
<p>Order #{{orderNumber}}</p>
<p>Total: ${{total}}</p>
<ul>
{{#each items}}
<li>{{this.name}} - ${{this.price}}</li>
{{/each}}
</ul>
`;
const result = await buildEmailTemplate(
baseTemplate,
orderTemplate,
{
orderNumber: '12345',
total: '99.99',
items: [
{ name: 'Product A', price: '49.99' },
{ name: 'Product B', price: '50.00' },
],
}
);Integration Status
- Logger: Optional - Logs compilation errors and validation warnings when provided
- Docs-Suite: Ready - Complete API documentation with examples
- NeverHub: Optional - Publishes template processing events when available
Logger Integration
import { EmailTemplateEngine } from '@bernierllc/email-template-engine';
import { Logger } from '@bernierllc/logger';
const logger = new Logger({ service: 'email-template-engine' });
const engine = new EmailTemplateEngine({ logger });
// Logger automatically logs:
// - Template compilation errors
// - Variable extraction issues
// - Text generation failuresPerformance
- Template compilation: <10ms for typical email templates (5KB)
- Complete template building: <50ms including text generation
- Variable extraction: <5ms for templates with 50+ variables
- Compilation cache available for repeated use
TypeScript Support
Full TypeScript definitions included:
import type {
BaseTemplate,
BuiltTemplate,
CompilationOptions,
TemplateResult,
TemplateValidationResult,
TemplateVariable,
TextGenerationOptions,
} from '@bernierllc/email-template-engine';See Also
- @bernierllc/email-template-service - Template CRUD and provider sync
- @bernierllc/email-manager - Complete email management suite
- @bernierllc/logger - Optional logging integration
License
Copyright (c) 2025 Bernier LLC. All rights reserved.
This package is licensed under a limited-use license. See LICENSE file for details.
