0
# Mustache.js
1
2
Mustache.js is a zero-dependency implementation of the Mustache template system in JavaScript. It provides logic-less templating with support for variable interpolation, sections, partials, and custom delimiters, compatible with web browsers, Node.js, and CouchDB views.
3
4
## Package Information
5
6
- **Package Name**: mustache
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install mustache`
10
11
## Core Imports
12
13
ESM (import):
14
```javascript
15
import Mustache from "mustache";
16
```
17
18
CommonJS (require):
19
```javascript
20
const Mustache = require("mustache");
21
// or
22
var Mustache = require("mustache");
23
```
24
25
AMD:
26
```javascript
27
define(["mustache"], function(Mustache) {
28
// Use Mustache
29
});
30
```
31
32
Browser global:
33
```html
34
<script src="https://unpkg.com/mustache@latest"></script>
35
<script>
36
// Mustache is available globally
37
</script>
38
```
39
40
## Basic Usage
41
42
```javascript
43
import Mustache from "mustache";
44
45
// Simple template rendering
46
const template = "Hello {{name}}!";
47
const view = { name: "World" };
48
const output = Mustache.render(template, view);
49
// Output: "Hello World!"
50
51
// Template with sections
52
const listTemplate = `
53
{{#users}}
54
<li>{{name}} - {{email}}</li>
55
{{/users}}
56
`;
57
const listView = {
58
users: [
59
{ name: "Alice", email: "alice@example.com" },
60
{ name: "Bob", email: "bob@example.com" }
61
]
62
};
63
const listOutput = Mustache.render(listTemplate, listView);
64
65
// Using partials
66
const partials = {
67
header: "<h1>{{title}}</h1>",
68
footer: "<footer>{{year}}</footer>"
69
};
70
const mainTemplate = "{{>header}}<p>Content</p>{{>footer}}";
71
const mainView = { title: "My Page", year: 2024 };
72
const result = Mustache.render(mainTemplate, mainView, partials);
73
```
74
75
## Architecture
76
77
Mustache.js is built around several key components:
78
79
- **Template Parser**: Converts template strings into token trees for efficient rendering
80
- **Context System**: Manages variable resolution and scope traversal
81
- **Writer Engine**: Renders token trees into final output strings
82
- **Caching Layer**: Stores parsed templates for performance optimization
83
- **Multi-Platform Support**: Works across CommonJS, AMD, ESM, and browser globals
84
85
## Capabilities
86
87
### Template Rendering
88
89
Primary function for rendering Mustache templates with data and optional partials.
90
91
```javascript { .api }
92
/**
93
* Renders the template with the given view, partials, and config
94
* @param {string} template - The Mustache template string
95
* @param {any} view - The view object containing data for rendering
96
* @param {object|function} [partials] - Optional object containing partial templates or function to load partials
97
* @param {object|array} [config] - Optional configuration object or array for custom tags/escaping
98
* @returns {string} The rendered string
99
*/
100
Mustache.render(template, view, partials, config)
101
```
102
103
**Usage Examples:**
104
105
```javascript
106
// Basic rendering
107
const output = Mustache.render("{{greeting}} {{name}}!", {
108
greeting: "Hello",
109
name: "World"
110
});
111
112
// With partials object
113
const partials = { user: "{{name}} ({{email}})" };
114
const result = Mustache.render("User: {{>user}}", {
115
name: "Alice",
116
email: "alice@example.com"
117
}, partials);
118
119
// With partials function
120
const partialLoader = (name) => {
121
const templates = {
122
header: "<h1>{{title}}</h1>",
123
footer: "<p>{{copyright}}</p>"
124
};
125
return templates[name];
126
};
127
const page = Mustache.render("{{>header}}Content{{>footer}}", {
128
title: "My Site",
129
copyright: "2024"
130
}, partialLoader);
131
132
// With custom configuration
133
const customTags = ["<%", "%>"];
134
const erbStyle = Mustache.render("<% name %>", { name: "Alice" }, {}, customTags);
135
136
// With escape configuration
137
const config = {
138
tags: ["{{", "}}"],
139
escape: (text) => text.toUpperCase() // Custom escaping
140
};
141
const escaped = Mustache.render("{{name}}", { name: "alice" }, {}, config);
142
```
143
144
### Template Pre-parsing
145
146
Pre-parses and caches templates for improved performance on repeated renders.
147
148
```javascript { .api }
149
/**
150
* Parses and caches the given template and returns the array of tokens
151
* @param {string} template - The Mustache template string to parse
152
* @param {string[]} [tags] - Optional array of opening and closing tag strings
153
* @returns {array} Array of parsed tokens
154
*/
155
Mustache.parse(template, tags)
156
```
157
158
**Usage Examples:**
159
160
```javascript
161
// Pre-parse for performance
162
const template = "Hello {{name}}!";
163
Mustache.parse(template);
164
165
// Later rendering uses cached version
166
const output = Mustache.render(template, { name: "World" });
167
168
// Pre-parse with custom tags
169
const erbTemplate = "Hello <% name %>!";
170
const tokens = Mustache.parse(erbTemplate, ["<%", "%>"]);
171
```
172
173
### Cache Management
174
175
Clears all cached parsed templates to free memory.
176
177
```javascript { .api }
178
/**
179
* Clears all cached templates in the default writer
180
* @returns {void}
181
*/
182
Mustache.clearCache()
183
```
184
185
**Usage Examples:**
186
187
```javascript
188
// Clear cache to free memory
189
Mustache.clearCache();
190
191
// Useful in long-running applications
192
setInterval(() => {
193
Mustache.clearCache();
194
}, 60000); // Clear cache every minute
195
```
196
197
### HTML Escaping
198
199
Configurable HTML escaping function for secure template rendering.
200
201
```javascript { .api }
202
/**
203
* HTML escaping function (can be overridden)
204
* @param {string} text - String to escape
205
* @returns {string} HTML-escaped string
206
*/
207
Mustache.escape(text)
208
```
209
210
**Usage Examples:**
211
212
```javascript
213
// Default HTML escaping
214
const escaped = Mustache.escape("<script>alert('xss')</script>");
215
// Result: "<script>alert('xss')</script>"
216
217
// Override escaping globally
218
Mustache.escape = function(text) {
219
return text; // Disable escaping
220
};
221
222
// Or use per-render configuration
223
const config = {
224
escape: (text) => text.replace(/</g, "<").replace(/>/g, ">")
225
};
226
Mustache.render("{{html}}", { html: "<b>bold</b>" }, {}, config);
227
```
228
229
### Template Delimiters
230
231
Configurable template delimiters for custom syntax.
232
233
```javascript { .api }
234
/**
235
* Default template delimiter tags
236
* @type {string[]} Array containing opening and closing delimiter strings
237
*/
238
Mustache.tags
239
```
240
241
**Usage Examples:**
242
243
```javascript
244
// View current tags
245
console.log(Mustache.tags); // ["{{", "}}"]
246
247
// Set custom tags globally
248
Mustache.tags = ["<%", "%>"];
249
const output = Mustache.render("<% name %>", { name: "Alice" });
250
251
// Reset to default
252
Mustache.tags = ["{{", "}}"];
253
254
// Or use per-render tags
255
const result = Mustache.render("<% greeting %>", { greeting: "Hello" }, {}, ["<%", "%>"]);
256
```
257
258
### Template Cache
259
260
Advanced cache management with custom storage strategies.
261
262
```javascript { .api }
263
/**
264
* Template cache storage object with get/set/clear methods
265
* @type {object} Cache object with set, get, clear methods
266
*/
267
Mustache.templateCache
268
269
/**
270
* Set custom template cache
271
* @param {object|undefined} cache - Cache object or undefined to disable caching
272
*/
273
Mustache.templateCache = cache
274
```
275
276
**Usage Examples:**
277
278
```javascript
279
// View current cache
280
console.log(Object.keys(Mustache.templateCache._cache));
281
282
// Custom cache implementation
283
const customCache = {
284
_storage: new Map(),
285
set(key, value) {
286
this._storage.set(key, value);
287
},
288
get(key) {
289
return this._storage.get(key);
290
},
291
clear() {
292
this._storage.clear();
293
}
294
};
295
Mustache.templateCache = customCache;
296
297
// Disable caching entirely
298
Mustache.templateCache = undefined;
299
```
300
301
### Library Metadata
302
303
Version and identification information.
304
305
```javascript { .api }
306
/**
307
* Library name identifier
308
* @type {string}
309
*/
310
Mustache.name
311
312
/**
313
* Library version string
314
* @type {string}
315
*/
316
Mustache.version
317
```
318
319
**Usage Examples:**
320
321
```javascript
322
console.log(`Using ${Mustache.name} version ${Mustache.version}`);
323
// Output: "Using mustache.js version 4.2.0"
324
```
325
326
## Advanced Usage
327
328
### Scanner Class
329
330
Low-level string scanner for custom template parsing.
331
332
```javascript { .api }
333
/**
334
* String scanner constructor for template parsing
335
* @param {string} string - String to scan
336
* @constructor
337
*/
338
new Mustache.Scanner(string)
339
340
/**
341
* Check if scanner is at end of string
342
* @returns {boolean} True if at end of string
343
*/
344
Scanner.prototype.eos()
345
346
/**
347
* Try to match regex at current position, advance if matched
348
* @param {RegExp} re - Regular expression to match
349
* @returns {string} Matched text or empty string
350
*/
351
Scanner.prototype.scan(re)
352
353
/**
354
* Scan until regex matches, return skipped content
355
* @param {RegExp} re - Regular expression to match
356
* @returns {string} Skipped content
357
*/
358
Scanner.prototype.scanUntil(re)
359
```
360
361
**Usage Examples:**
362
363
```javascript
364
const scanner = new Mustache.Scanner("Hello {{name}}!");
365
366
// Scan until opening tag
367
const text = scanner.scanUntil(/\{\{/);
368
console.log(text); // "Hello "
369
370
// Check if at end
371
console.log(scanner.eos()); // false
372
373
// Scan opening tag
374
const tag = scanner.scan(/\{\{/);
375
console.log(tag); // "{{"
376
```
377
378
### Context Class
379
380
Template rendering context for variable resolution.
381
382
```javascript { .api }
383
/**
384
* Context constructor for template rendering
385
* @param {any} view - View object for this context
386
* @param {Context} [parentContext] - Optional parent context
387
* @constructor
388
*/
389
new Mustache.Context(view, parentContext)
390
391
/**
392
* Create child context with new view
393
* @param {any} view - View object for child context
394
* @returns {Context} New child context
395
*/
396
Context.prototype.push(view)
397
398
/**
399
* Look up variable name in context hierarchy
400
* @param {string} name - Variable name to look up
401
* @returns {any} Variable value or undefined
402
*/
403
Context.prototype.lookup(name)
404
```
405
406
**Usage Examples:**
407
408
```javascript
409
// Create context
410
const context = new Mustache.Context({ name: "Alice", age: 30 });
411
412
// Look up values
413
console.log(context.lookup("name")); // "Alice"
414
console.log(context.lookup("missing")); // undefined
415
416
// Create child context
417
const childContext = context.push({ name: "Bob", city: "NYC" });
418
console.log(childContext.lookup("name")); // "Bob" (child overrides)
419
console.log(childContext.lookup("age")); // 30 (inherited from parent)
420
```
421
422
### Writer Class
423
424
Advanced template writer for custom rendering workflows.
425
426
```javascript { .api }
427
/**
428
* Writer constructor for template rendering
429
* @constructor
430
*/
431
new Mustache.Writer()
432
433
/**
434
* Clear this writer's template cache
435
* @returns {void}
436
*/
437
Writer.prototype.clearCache()
438
439
/**
440
* Parse template into tokens
441
* @param {string} template - Template string to parse
442
* @param {string[]} [tags] - Optional custom tags
443
* @returns {array} Array of tokens
444
*/
445
Writer.prototype.parse(template, tags)
446
447
/**
448
* Render template with view and options
449
* @param {string} template - Template string
450
* @param {any} view - View object with data
451
* @param {any} [partials] - Optional partials
452
* @param {any} [config] - Optional configuration
453
* @returns {string} Rendered output
454
*/
455
Writer.prototype.render(template, view, partials, config)
456
457
/**
458
* Render pre-parsed tokens
459
* @param {array} tokens - Pre-parsed tokens
460
* @param {Context} context - Rendering context
461
* @param {any} [partials] - Optional partials
462
* @param {string} [originalTemplate] - Original template string
463
* @param {any} [config] - Optional configuration
464
* @returns {string} Rendered output
465
*/
466
Writer.prototype.renderTokens(tokens, context, partials, originalTemplate, config)
467
```
468
469
**Usage Examples:**
470
471
```javascript
472
// Create custom writer
473
const writer = new Mustache.Writer();
474
475
// Use writer for rendering
476
const template = "Hello {{name}}!";
477
const tokens = writer.parse(template);
478
const context = new Mustache.Context({ name: "World" });
479
const output = writer.renderTokens(tokens, context);
480
console.log(output); // "Hello World!"
481
482
// Clear only this writer's cache
483
writer.clearCache();
484
```
485
486
## Template Syntax
487
488
### Variables
489
490
```javascript
491
// HTML-escaped output
492
"{{name}}" // Outputs escaped value
493
494
// Unescaped output
495
"{{{name}}}" // Outputs raw HTML
496
"{{&name}}" // Alternative unescaped syntax
497
498
// Dot notation
499
"{{user.name}}" // Access nested properties
500
"{{user.address.city}}" // Deep nesting
501
```
502
503
### Sections
504
505
```javascript
506
// Conditional sections
507
"{{#person}}Hello {{name}}!{{/person}}" // Renders if person exists
508
509
// Iteration sections
510
"{{#users}}{{name}}: {{email}}{{/users}}" // Repeats for each user
511
512
// Inverted sections
513
"{{^users}}No users found{{/users}}" // Renders if users is empty/false
514
```
515
516
### Partials
517
518
```javascript
519
// Include partial template
520
"{{>header}}" // Includes header partial
521
"{{>user}}" // Includes user partial with current context
522
```
523
524
### Comments
525
526
```javascript
527
"{{! This is a comment }}" // Comments are not rendered
528
```
529
530
### Custom Delimiters
531
532
```javascript
533
// Change delimiters within template
534
"{{=<% %>=}}"
535
"<% name %>" // Now uses ERB-style delimiters
536
"<%={{ }}=%>" // Switch back to default
537
```
538
539
## Command Line Interface
540
541
Mustache.js includes a command-line tool for template rendering.
542
543
### Installation
544
545
```bash
546
npm install -g mustache
547
```
548
549
### Usage
550
551
```bash
552
# Basic syntax
553
mustache <view> <template> [output]
554
555
# Basic usage - render to stdout
556
mustache view.json template.mustache
557
558
# Render to output file
559
mustache view.json template.mustache output.html
560
561
# Using stdin for view data
562
cat view.json | mustache - template.mustache > output.html
563
echo '{"name": "World"}' | mustache - template.mustache
564
565
# With single partial
566
mustache -p header.mustache view.json main.mustache
567
568
# With multiple partials
569
mustache -p header.mustache -p footer.mustache view.json main.mustache
570
mustache -p partials/nav.mustache -p partials/sidebar.mustache data.json page.mustache
571
572
# Show version
573
mustache --version
574
mustache -v
575
```
576
577
### View Data Formats
578
579
The CLI accepts view data in multiple formats:
580
581
```bash
582
# JSON file
583
mustache data.json template.mustache
584
585
# JavaScript module (exports object)
586
mustache data.js template.mustache
587
mustache data.cjs template.mustache
588
589
# Stdin with dash
590
echo '{"name": "World"}' | mustache - template.mustache
591
cat view.json | mustache - template.mustache
592
```
593
594
**Note:** Partial names are derived from the filename without the `.mustache` extension. For example, `-p header.mustache` creates a partial named `header`.
595
596
## Error Handling
597
598
Common errors and their meanings:
599
600
```javascript
601
// Template syntax errors
602
try {
603
Mustache.render("{{#section}}", {});
604
} catch (error) {
605
// Error: Unclosed section "section" at position X
606
}
607
608
// Invalid tags
609
try {
610
Mustache.render("template", {}, {}, ["{{", ">>"]);
611
} catch (error) {
612
// Error: Invalid tags: {{,>>
613
}
614
615
// Type validation
616
try {
617
Mustache.render(123, {});
618
} catch (error) {
619
// TypeError: Invalid template! Template should be a "string"
620
}
621
```
622
623
## TypeScript Support
624
625
For TypeScript users, type definitions are available via `@types/mustache`:
626
627
```bash
628
npm install --save-dev @types/mustache
629
```
630
631
This provides full type safety and IntelliSense support for all Mustache.js APIs.