npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

ts-templater

v0.4.2

Published

A flexible TypeScript library for dynamic string templating.

Readme

🎯 TS-Templater

TypeScript License Tests Coverage


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 FunctionNew!

// 🔄 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:

  1. 🍴 Fork the repository
  2. 🌟 Create a feature branch
  3. Add tests for new features
  4. 📝 Update documentation
  5. 🚀 Submit a pull request

🆘 Support & Community


Made with ❤️ by the TS-Templater team

Star us on GitHub if this project helped you!