Simple micro templating library for JavaScript that enables string interpolation with placeholder substitution
npx @tessl/cli install tessl/npm-pupa@2.1.00
# Pupa
1
2
Pupa is a simple micro templating library for JavaScript that enables string interpolation with placeholder substitution. It supports both object property access and array indexing through a clean brace syntax, includes automatic HTML entity encoding for security, and handles nested object property access through dot notation.
3
4
## Package Information
5
6
- **Package Name**: pupa
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Node.js Requirements**: >=8
10
- **Installation**: `npm install pupa`
11
12
## Core Imports
13
14
```javascript
15
const pupa = require('pupa');
16
```
17
18
For TypeScript:
19
20
```typescript
21
import pupa = require('pupa');
22
```
23
24
## Basic Usage
25
26
```javascript
27
const pupa = require('pupa');
28
29
// Object property interpolation
30
pupa('The mobile number of {name} is {phone.mobile}', {
31
name: 'Sindre',
32
phone: {
33
mobile: '609 24 363'
34
}
35
});
36
//=> 'The mobile number of Sindre is 609 24 363'
37
38
// Array index interpolation
39
pupa('I like {0} and {1}', ['๐ฆ', '๐ฎ']);
40
//=> 'I like ๐ฆ and ๐ฎ'
41
42
// HTML-safe interpolation (prevents XSS)
43
pupa('I like {{0}} and {{1}}', ['<br>๐ฆ</br>', '<i>๐ฎ</i>']);
44
//=> 'I like <br>๐ฆ</br> and <i>๐ฎ</i>'
45
```
46
47
## Capabilities
48
49
### Template Interpolation
50
51
Main templating function that interpolates placeholders in templates with data values. Supports two interpolation modes: plain text replacement and HTML-escaped replacement for security.
52
53
```javascript { .api }
54
/**
55
* Simple micro templating function for string interpolation
56
* @param {string} template - Text with placeholders for data properties
57
* @param {object|unknown[]} data - Data to interpolate into template
58
* @returns {string} The template with placeholders replaced by corresponding data values
59
* @throws {TypeError} If template is not a string
60
* @throws {TypeError} If data is not an object or array
61
*/
62
function pupa(template, data);
63
```
64
65
**Template Syntax:**
66
67
- `{key}` - Plain interpolation: replaces with string representation of value
68
- `{{key}}` - HTML-escaped interpolation: replaces with HTML entity-encoded value to prevent XSS
69
- `{object.property}` - Nested object property access using dot notation
70
- `{0}`, `{1}` - Array index access using numeric keys
71
72
**Parameter Details:**
73
74
- **template** (string): Text containing placeholders in `{key}` or `{{key}}` format
75
- Supports nested property access: `{user.profile.name}`
76
- Supports array indexing: `{0}`, `{1}`, etc.
77
- Case-sensitive property matching
78
- Invalid placeholders are left unchanged in output
79
80
- **data** (object | unknown[]): Data source for placeholder replacement
81
- Objects: Properties accessed by key name or dot notation path
82
- Arrays: Elements accessed by numeric index
83
- Missing properties/indices resolve to empty string
84
- All values converted to string representation
85
86
**Return Value:**
87
- Returns processed template string with placeholders replaced
88
- HTML entities encoded in double-brace placeholders (`{{key}}`)
89
- Plain string values in single-brace placeholders (`{key}`)
90
91
**Error Handling:**
92
- Throws `TypeError` if template parameter is not a string
93
- Throws `TypeError` if data parameter is not an object or array
94
- Gracefully handles missing properties by substituting empty string
95
- Invalid placeholder formats are left unchanged in output
96
97
**Usage Examples:**
98
99
```javascript
100
const pupa = require('pupa');
101
102
// Nested object properties
103
pupa('User {user.name} has email {user.contact.email}', {
104
user: {
105
name: 'Alice',
106
contact: {
107
email: 'alice@example.com'
108
}
109
}
110
});
111
//=> 'User Alice has email alice@example.com'
112
113
// Array access by index
114
pupa('Items: {0} and {1}', ['Widget', 'Gadget']);
115
//=> 'Items: Widget and Gadget'
116
117
// Object property access
118
pupa('Item: {name} costs ${price}', { name: 'Widget', price: 29.99 });
119
//=> 'Item: Widget costs $29.99'
120
121
// HTML escaping for security
122
pupa('Message: {{userInput}}', {
123
userInput: '<script>alert("xss")</script>'
124
});
125
//=> 'Message: <script>alert("xss")</script>'
126
127
// Missing properties become empty strings
128
pupa('Hello {name}, your score is {score}', { name: 'Bob' });
129
//=> 'Hello Bob, your score is '
130
131
// Type coercion examples
132
pupa('Count: {count}, Active: {active}', {
133
count: 42,
134
active: true
135
});
136
//=> 'Count: 42, Active: true'
137
```
138
139
**Key Features:**
140
- **Lazy evaluation**: Templates expand at execution time, not creation time
141
- **Security**: Double-brace syntax automatically escapes HTML entities to prevent XSS attacks
142
- **Flexibility**: Supports both object property and array index access
143
- **Error resilience**: Gracefully handles missing data with empty string substitution
144
- **Nested access**: Dot notation for deep object property traversal
145
- **User-supplied templates**: Safe for dynamic template strings from external sources
146
- **Performance**: Efficient regex-based parsing suitable for high-frequency template rendering