ts-templater
v0.4.2
Published
A flexible TypeScript library for dynamic string templating.
Maintainers
Readme
🎯 TS-Templater
✨ Why Choose TS-Templater?
📦 Installation
# 🚀 Get started in seconds
npm install ts-templater
# 🔥 Or with yarn
yarn add ts-templater🅰️ Angular/Browser Setup
When using ts-templater in Angular or browser environments, dayjs locales must be imported manually:
// Import the library
import { TsTemplater } from 'ts-templater';
import dayjs from 'dayjs';
// Import needed locales
import 'dayjs/locale/it'; // Italian
import 'dayjs/locale/fr'; // French
import 'dayjs/locale/es'; // Spanish
// Use the templater
const templater = new TsTemplater();
templater.changeDayjsLocale('it'); // Switch to Italian🚀 Quick Start
import { TsTemplater } from 'ts-templater';
const templater = new TsTemplater();
const data = {
user: { name: '🎯 John', age: 30 },
products: [
{ name: '💻 Laptop', price: 999.99 },
{ name: '🖱️ Mouse', price: 29.99 }
]
};
// ✨ String templating
const greeting = templater.parse('Hello {user.name}!', data);
// 🎉 Result: "Hello 🎯 John!"
// 🔥 Type-preserving evaluation
const age = templater.evaluate('user.age', data);
// ⚡ Result: 30 (number, not string)🎨 Core Concepts
🎭 Dual Modes Explained
| Method | Purpose | Return Type | Use Case |
|--------|---------|-------------|----------|
| parse() | 📝 String templating | Always string | Templates, emails, UI |
| evaluate() | 🔢 Data processing | Original types | Calculations, APIs |
// 📝 parse() - For templating (string output)
const template = templater.parse('Price: {price}€', { price: 42.5 });
// → "Price: 42.5€"
// 🔢 evaluate() - For data processing (type preserved)
const price = templater.evaluate('price', { price: 42.5 });
// → 42.5 (number)🔧 Function Syntax Types
| Syntax | Description | Example |
|--------|-------------|---------|
| @Function | 🎯 Simple functions | {@Date\|{date}\|DD/MM/YYYY} |
| #@Function | 📊 Data-aware | {#@ArraySum\|items\|{price}} |
| !@Function | 🔄 Legacy syntax | {!@Math\|+\|5\|3} |
🎨 Basic Templating
const data = {
name: '🌟 Alice',
profile: { age: 25, city: '🏛️ Rome' },
tags: ['👩💻 developer', '📘 typescript', '⚛️ react']
};
// 🔹 Simple properties
templater.parse('{name}', data); // → "🌟 Alice"
// 🔹 Nested properties
templater.parse('{profile.age}', data); // → "25"
// 🔹 Array by index
templater.parse('{tags[0]}', data); // → "👩💻 developer"
// 🔹 Array special positions
templater.parse('{tags[first]}', data); // → "👩💻 developer"
templater.parse('{tags[last]}', data); // → "⚛️ react"const users = [
{ id: 1, name: '👑 John', role: 'admin' },
{ id: 2, name: '👤 Jane', role: 'user' }
];
// 🎯 Find by field value
templater.parse('{users[2,id].name}', { users }); // → "👤 Jane"
templater.parse('{users[admin,role].name}', { users }); // → "👑 John"🧮 Functions Showcase
📅 Date & Time
// ⏰ Basic formatting
{@Date|2023-12-25|DD/MM/YYYY}
// → "25/12/2023"
// 🌟 Custom format
{@Date|{timestamp}|dddd, MMMM Do YYYY}
// → "Monday, December 25th 2023"💰 Currency & Numbers
// 💵 Currency formatting
{@Currency|1234.56} // → "€1,234.56"
{@Currency|{price}|USD} // → "$1,234.56"
{@Currency|{amount}|GBP|en-GB} // → "£1,234.56"
// 🔢 Number conversion
{@Number|{stringValue}} // Converts to number
{@Bool|{value}} // Converts to boolean🧮 Mathematics
// ➕ Basic math
{@Math|+|{a}|{b}} // Addition
{@Math|-|10|3} // → 7
{@Math|*|{price}|1.22} // 22% markup
{@Math|/|{total}|{count}} // Average
{@Math|%|{number}|10} // Modulo
{@Math|**|2|3} // Power (2³ = 8)🔀 Conditional Logic
// 🤔 If statements
{@If|{age}>=18|🔞 Adult|👶 Minor}
// 🔄 Switch statements
{@Switch|{type}|user:👤 User|admin:👑 Admin}
// ✅ Boolean operations
{@Bool|{value}} // Convert to boolean
{@Not|{isActive}} // Negate boolean🔍 String Operations
// 🔎 Contains check
{@Contains|{filename}|.jpg|📸 Image|📄 Document}
// 📏 Padding
{@PadStart|{id}|5|0} // → "00123"
{@PadEnd|{name}|10|.} // → "John......"✂️ Split Function ⭐ New!
// 🔄 Split JSON strings into arrays
{#@Split|{"id":1,"name":"A"};{"id":2,"name":"B"}|;}
// → [{id:1,name:"A"}, {id:2,name:"B"}]
// 🎯 Use with different delimiters
{#@Split|{"a":1}###{"b":2}|###}
// → [{a:1}, {b:2}]📊 Array Processing
const data = {
items: [
{ name: '💻 Laptop', price: 999 },
{ name: '🖱️ Mouse', price: 29 }
]
};
// 🔗 Concatenate array elements
{#@ArrayConcat|items|{name}: €{price}\n}
// → "💻 Laptop: €999\n🖱️ Mouse: €29\n"
// ➕ Sum array values
{#@ArraySum|items|{price}} // → "1028"
{#@ArraySum|items|{@Math|*|{price}|1.22}} // Sum with 22% tax🎯 Advanced Examples
const emailTemplate = `
🎉 Hello {user.name}!
📦 Your order {order.id} from {@Date|{order.date}|DD/MM/YYYY} has been confirmed.
🛍️ Items:
{#@ArrayConcat|order.items|• {name} x{qty} - {@Currency|{@Math|*|{price}|{qty}}}
}
💰 Total: {@Currency|{order.total}}
🙏 Thank you for your purchase!
`;const report = templater.parse(`
📈 SALES REPORT - {month}
💰 Revenue: {@Currency|{stats.totalSales}}
📦 Orders: {stats.orders}
📊 Avg Order: {@Currency|{stats.avgOrder}}
🏆 TOP PRODUCTS:
{#@ArrayConcat|topProducts|{@PadStart|{@Math|+|{$index}|1}|2| }. {name}: {@Currency|{sales}}
}
📈 Performance: {@If|{stats.totalSales}>10000|🟢 Excellent|🟡 Good}
`, reportData);🔧 Configuration
🌍 Localization
// 🌎 Set language for date formatting and currency
const templater = new TsTemplater('it'); // Italian locale
// 🔄 Change locale at runtime
await templater.changeDayjsLocale('fr');🔌 Custom Functions
// ⚡ Add your own functions
templater.setFunctions({
customFormat: (params) => `✨ Custom: ${params[0]}`,
calculateDiscount: (data, params) => {
const price = data[params[0]];
const discount = parseFloat(params[1]);
return price * (1 - discount / 100);
}
});📚 Documentation
For detailed documentation on specific features:
- 📋 Custom Functions Guide - Complete guide for using
setFunctions()to extend TsTemplater with custom logic - ⚡ Cache System - Detailed documentation of the intelligent caching system for performance optimization
🧪 Testing Excellence
135/135 tests passing with 100% coverage
✅ All core functions
✅ Edge cases and error handling
✅ Type preservation
✅ Complex nested scenarios
✅ Performance and memory usage
# 🧪 Run tests
npm test📄 License
🔓 MIT License - Free for commercial and personal use
✅ What you CAN do:
- 💼 Commercial use - Use in commercial projects
- 🔧 Modify - Change the source code
- 📦 Distribute - Share the library
- 🔒 Private use - Use in private projects
❌ What we DON'T provide:
- 🛡️ Warranty - No warranty provided
- ⚖️ Liability - Authors not liable for damages
🤝 Contributing
Contributions welcome! Please:
- 🍴 Fork the repository
- 🌟 Create a feature branch
- ✅ Add tests for new features
- 📝 Update documentation
- 🚀 Submit a pull request
🆘 Support & Community
- 📚 Documentation: Check this README
- 🐛 Issues: GitHub Issues
- 💬 Discussions: GitHub Discussions
Made with ❤️ by the TS-Templater team
⭐ Star us on GitHub if this project helped you!
