@454creative/easy-email
Version:
A framework-agnostic email service library for Node.js with observability and monitoring
82 lines • 2.85 kB
JavaScript
;
/**
* Simple template engine for email templates
*
* Provides functions for rendering templates with context variables
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TemplateEngine = void 0;
exports.renderString = renderString;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
/**
* Template engine class for rendering email templates
*/
class TemplateEngine {
/**
* Create a template engine instance
*
* @param templatesDir - Directory containing template files
*/
constructor(templatesDir) {
this.templatesDir = templatesDir;
}
/**
* Render a template with context variables
*
* @param templateName - Name of the template (without extension)
* @param context - Variables to inject into the template
* @returns string - Rendered template
*/
render(templateName, context = {}) {
const templatePath = path_1.default.join(this.templatesDir, `${templateName}.html`);
try {
let template = fs_1.default.readFileSync(templatePath, 'utf8');
return this.renderTemplate(template, context);
}
catch (error) {
console.error(`Failed to render template ${templateName}:`, error);
throw new Error(`Template rendering failed: ${error instanceof Error ? error.message : String(error)}`);
}
}
/**
* Check if a template exists
*
* @param templateName - Name of the template (without extension)
* @returns boolean - True if template exists
*/
templateExists(templateName) {
const templatePath = path_1.default.join(this.templatesDir, `${templateName}.html`);
return fs_1.default.existsSync(templatePath);
}
/**
* Render template content with context variables
* @private
*/
renderTemplate(template, context) {
let result = template;
// Replace variables in the template
Object.keys(context).forEach(key => {
const value = context[key];
const regex = new RegExp(`{{\\s*${key}\\s*}}`, 'g');
result = result.replace(regex, String(value));
});
return result;
}
}
exports.TemplateEngine = TemplateEngine;
/**
* Render a template string with context variables
*
* @param template - Template string with {{variable}} placeholders
* @param context - Variables to inject into the template
* @returns string - Rendered template
*/
function renderString(template, context = {}) {
const engine = new TemplateEngine('');
return engine.renderTemplate(template, context);
}
//# sourceMappingURL=template-engine.js.map