0
# String Template
1
2
String Template is a simple, lightweight JavaScript string templating library that enables placeholder-based string formatting using named object properties, indexed array elements, or variadic arguments. It provides high-performance template compilation options and supports escaping syntax for literal braces.
3
4
## Package Information
5
6
- **Package Name**: string-template
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install string-template`
10
11
## Core Imports
12
13
```javascript
14
var format = require("string-template");
15
var compile = require("string-template/compile");
16
```
17
18
## Basic Usage
19
20
```javascript
21
var format = require("string-template");
22
23
// Object-based placeholders
24
var greeting = format("Hello {name}, you have {count} unread messages", {
25
name: "Robert",
26
count: 12
27
});
28
// Result: "Hello Robert, you have 12 unread messages"
29
30
// Array-based placeholders
31
var message = format("Hello {0}, you have {1} unread messages", ["Alice", 5]);
32
// Result: "Hello Alice, you have 5 unread messages"
33
34
// Variadic arguments
35
var text = format("Hello {0}, you have {1} unread messages", "Bob", 3);
36
// Result: "Hello Bob, you have 3 unread messages"
37
38
// Escaping placeholders
39
var escaped = format("Use {{placeholder}} syntax for templates");
40
// Result: "Use {placeholder} syntax for templates"
41
```
42
43
## Capabilities
44
45
### String Template Function
46
47
Main templating function that replaces placeholders in strings with provided values.
48
49
```javascript { .api }
50
/**
51
* Template function for string interpolation with placeholder substitution
52
* @param {string} string - Template string containing {placeholder} markers
53
* @param {object|array} args - Single object/array OR multiple arguments
54
* @returns {string} Formatted string with placeholders replaced
55
*/
56
function template(string, args);
57
```
58
59
**Placeholder Syntax:**
60
- Format: `{key}` where key matches pattern `[0-9a-zA-Z_]+`
61
- Escaping: `{{key}}` renders as literal `{key}`
62
- Missing values: Render as empty string `""`
63
- Null/undefined values: Render as empty string `""`
64
65
**Parameter Patterns:**
66
- **Object hash**: `template(str, {key: value, key2: value2})`
67
- **Array indexing**: `template(str, [value1, value2])`
68
- **Multiple arguments**: `template(str, value1, value2, value3)`
69
70
**Important Behavior:**
71
- Only own properties are accessible (uses `hasOwnProperty` check)
72
- Array prototype methods like `splice` are not accessible as placeholders
73
- Invalid arguments fallback to empty object `{}`
74
75
**Usage Examples:**
76
77
```javascript
78
var format = require("string-template");
79
80
// Object properties
81
var result1 = format("User {name} has {role} access", {
82
name: "Sarah",
83
role: "admin"
84
});
85
86
// Array indices
87
var result2 = format("Processing {0} of {1} items", [25, 100]);
88
89
// Multiple arguments
90
var result3 = format("Error {0}: {1}", "404", "Not Found");
91
92
// Missing values become empty strings
93
var result4 = format("Hello {name}{suffix}", { name: "World" });
94
// Result: "Hello World"
95
96
// Escaped braces
97
var result5 = format("Template: {{name}} becomes {name}", { name: "value" });
98
// Result: "Template: {name} becomes value"
99
100
// Array prototype methods are not accessible
101
var result6 = format("Function{splice}", []);
102
// Result: "Function" (splice is not accessible)
103
104
// Invalid arguments fallback gracefully
105
var result7 = format("Hello {name}", null);
106
// Result: "Hello" (null becomes empty object)
107
```
108
109
### Template Compilation
110
111
Compiles template strings into reusable functions for improved performance with repeated usage.
112
113
```javascript { .api }
114
/**
115
* Compiles a template string into a reusable template function
116
* @param {string} string - Template string with {placeholder} syntax
117
* @param {boolean} [inline] - If truthy, generates optimized function using new Function
118
* @returns {function} Compiled template function accepting single object/array or multiple arguments
119
*/
120
function compile(string, inline);
121
```
122
123
**Compilation Modes:**
124
- **Standard compilation**: Returns template function using string replacement
125
- **Inline compilation**: Uses `new Function` for maximum performance optimization
126
127
**Generated Function Interface:**
128
- Accepts same parameter patterns as main template function
129
- Returns formatted string
130
- Can be called with object hash, array, or multiple arguments
131
- Non-inline mode: Uses string concatenation (safer, slower)
132
- Inline mode: Uses `new Function` for maximum performance
133
134
**Usage Examples:**
135
136
```javascript
137
var compile = require("string-template/compile");
138
139
// Standard compilation
140
var greetingTemplate = compile("Hello {0}, you have {1} unread messages");
141
var greeting1 = greetingTemplate("Robert", 12);
142
var greeting2 = greetingTemplate("Alice", 3);
143
144
// Inline compilation (optimized)
145
var optimizedTemplate = compile("Welcome {name} to {site}!", true);
146
var welcome = optimizedTemplate({ name: "John", site: "our website" });
147
148
// Array usage with compiled template
149
var listTemplate = compile("Item {0}: {1}");
150
var items = ["apple", "banana", "cherry"];
151
for (var i = 0; i < items.length; i++) {
152
console.log(listTemplate(i + 1, items[i]));
153
}
154
```
155
156
## Error Handling
157
158
String Template follows a graceful degradation approach:
159
160
- **Missing object properties**: Render as empty string
161
- **Array index out of bounds**: Render as empty string
162
- **Invalid arguments**: Fallback to empty object `{}` when no `hasOwnProperty` method
163
- **Null/undefined values**: Render as empty string
164
- **Array prototype access**: Blocked by `hasOwnProperty` check (e.g., `splice`, `length`)
165
- **No exceptions thrown**: Functions handle all edge cases gracefully
166
- **Template compilation errors**: Non-inline mode provides safer fallback than inline
167
168
## Browser Compatibility
169
170
- **Internet Explorer 8+**: Full support
171
- **All modern browsers**: Full support
172
- **Node.js**: Full support
173
- **Zero dependencies**: No external runtime dependencies
174
- **Environment agnostic**: Works in any JavaScript environment
175
176
## Performance Notes
177
178
- **Template compilation**: Pre-processes templates for repeated use
179
- **Inline compilation**: Uses `new Function` for optimal performance
180
- **Regex-based replacement**: Efficient placeholder matching with `/\{([0-9a-zA-Z_]+)\}/g`
181
- **Memory efficient**: Minimal overhead for template processing