2 * mustache.js - Logic-less {{mustache}} templates with JavaScript
3 * http://github.com/janl/mustache.js
6 /*global define: false Mustache: true*/
8 (function defineMustache (global
, factory
) {
9 if (typeof exports
=== 'object' && exports
&& typeof exports
.nodeName
!== 'string') {
10 factory(exports
); // CommonJS
11 } else if (typeof define
=== 'function' && define
.amd
) {
12 define(['exports'], factory
); // AMD
15 factory(global
.Mustache
); // script, wsh, asp
17 }(this, function mustacheFactory (mustache
) {
19 var objectToString
= Object
.prototype.toString
;
20 var isArray
= Array
.isArray
|| function isArrayPolyfill (object
) {
21 return objectToString
.call(object
) === '[object Array]';
24 function isFunction (object
) {
25 return typeof object
=== 'function';
29 * More correct typeof string handling array
30 * which normally returns typeof 'object'
32 function typeStr (obj
) {
33 return isArray(obj
) ? 'array' : typeof obj
;
36 function escapeRegExp (string
) {
37 return string
.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
41 * Null safe way of checking whether or not an object,
42 * including its prototype, has a given property
44 function hasProperty (obj
, propName
) {
45 return obj
!= null && typeof obj
=== 'object' && (propName
in obj
);
49 * Safe way of detecting whether or not the given thing is a primitive and
50 * whether it has the given property
52 function primitiveHasOwnProperty (primitive
, propName
) {
55 && typeof primitive
!== 'object'
56 && primitive
.hasOwnProperty
57 && primitive
.hasOwnProperty(propName
)
61 // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
62 // See https://github.com/janl/mustache.js/issues/189
63 var regExpTest
= RegExp
.prototype.test
;
64 function testRegExp (re
, string
) {
65 return regExpTest
.call(re
, string
);
68 var nonSpaceRe
= /\S/;
69 function isWhitespace (string
) {
70 return !testRegExp(nonSpaceRe
, string
);
84 function escapeHtml (string
) {
85 return String(string
).replace(/[&<>"'`=\/]/g, function fromEntityMap (s
) {
92 var equalsRe
= /\s*=/;
93 var curlyRe
= /\s*\}/;
94 var tagRe
= /#|\^|\/|>|\{|&|=|!/;
97 * Breaks up the given `template` string into a tree of tokens. If the `tags`
98 * argument is given here it must be an array with two string values: the
99 * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
100 * course, the default is to use mustaches (i.e. mustache.tags).
102 * A token is an array with at least 4 elements. The first element is the
103 * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
104 * did not contain a symbol (i.e. {{myValue}}) this element is "name". For
105 * all text that appears outside a symbol this element is "text".
107 * The second element of a token is its "value". For mustache tags this is
108 * whatever else was inside the tag besides the opening symbol. For text tokens
109 * this is the text itself.
111 * The third and fourth elements of the token are the start and end indices,
112 * respectively, of the token in the original template.
114 * Tokens that are the root node of a subtree contain two more elements: 1) an
115 * array of tokens in the subtree and 2) the index in the original template at
116 * which the closing tag for that section begins.
118 function parseTemplate (template
, tags
) {
122 var sections
= []; // Stack to hold section tokens
123 var tokens
= []; // Buffer to hold the tokens
124 var spaces
= []; // Indices of whitespace tokens on the current line
125 var hasTag
= false; // Is there a {{tag}} on the current line?
126 var nonSpace
= false; // Is there a non-space char on the current line?
128 // Strips all whitespace tokens array for the current line
129 // if there was a {{#tag}} on it and otherwise only space.
130 function stripSpace () {
131 if (hasTag
&& !nonSpace
) {
132 while (spaces
.length
)
133 delete tokens
[spaces
.pop()];
142 var openingTagRe
, closingTagRe
, closingCurlyRe
;
143 function compileTags (tagsToCompile
) {
144 if (typeof tagsToCompile
=== 'string')
145 tagsToCompile
= tagsToCompile
.split(spaceRe
, 2);
147 if (!isArray(tagsToCompile
) || tagsToCompile
.length
!== 2)
148 throw new Error('Invalid tags: ' + tagsToCompile
);
150 openingTagRe
= new RegExp(escapeRegExp(tagsToCompile
[0]) + '\\s*');
151 closingTagRe
= new RegExp('\\s*' + escapeRegExp(tagsToCompile
[1]));
152 closingCurlyRe
= new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile
[1]));
155 compileTags(tags
|| mustache
.tags
);
157 var scanner
= new Scanner(template
);
159 var start
, type
, value
, chr
, token
, openSection
;
160 while (!scanner
.eos()) {
163 // Match any text between tags.
164 value
= scanner
.scanUntil(openingTagRe
);
167 for (var i
= 0, valueLength
= value
.length
; i
< valueLength
; ++i
) {
168 chr
= value
.charAt(i
);
170 if (isWhitespace(chr
)) {
171 spaces
.push(tokens
.length
);
176 tokens
.push([ 'text', chr
, start
, start
+ 1 ]);
179 // Check for whitespace on the current line.
185 // Match the opening tag.
186 if (!scanner
.scan(openingTagRe
))
192 type
= scanner
.scan(tagRe
) || 'name';
193 scanner
.scan(whiteRe
);
195 // Get the tag value.
197 value
= scanner
.scanUntil(equalsRe
);
198 scanner
.scan(equalsRe
);
199 scanner
.scanUntil(closingTagRe
);
200 } else if (type
=== '{') {
201 value
= scanner
.scanUntil(closingCurlyRe
);
202 scanner
.scan(curlyRe
);
203 scanner
.scanUntil(closingTagRe
);
206 value
= scanner
.scanUntil(closingTagRe
);
209 // Match the closing tag.
210 if (!scanner
.scan(closingTagRe
))
211 throw new Error('Unclosed tag at ' + scanner
.pos
);
213 token
= [ type
, value
, start
, scanner
.pos
];
216 if (type
=== '#' || type
=== '^') {
217 sections
.push(token
);
218 } else if (type
=== '/') {
219 // Check section nesting.
220 openSection
= sections
.pop();
223 throw new Error('Unopened section "' + value
+ '" at ' + start
);
225 if (openSection
[1] !== value
)
226 throw new Error('Unclosed section "' + openSection
[1] + '" at ' + start
);
227 } else if (type
=== 'name' || type
=== '{' || type
=== '&') {
229 } else if (type
=== '=') {
230 // Set the tags for the next time around.
235 // Make sure there are no open sections when we're done.
236 openSection
= sections
.pop();
239 throw new Error('Unclosed section "' + openSection
[1] + '" at ' + scanner
.pos
);
241 return nestTokens(squashTokens(tokens
));
245 * Combines the values of consecutive text tokens in the given `tokens` array
248 function squashTokens (tokens
) {
249 var squashedTokens
= [];
251 var token
, lastToken
;
252 for (var i
= 0, numTokens
= tokens
.length
; i
< numTokens
; ++i
) {
256 if (token
[0] === 'text' && lastToken
&& lastToken
[0] === 'text') {
257 lastToken
[1] += token
[1];
258 lastToken
[3] = token
[3];
260 squashedTokens
.push(token
);
266 return squashedTokens
;
270 * Forms the given array of `tokens` into a nested tree structure where
271 * tokens that represent a section have two additional items: 1) an array of
272 * all tokens that appear in that section and 2) the index in the original
273 * template that represents the end of that section.
275 function nestTokens (tokens
) {
276 var nestedTokens
= [];
277 var collector
= nestedTokens
;
281 for (var i
= 0, numTokens
= tokens
.length
; i
< numTokens
; ++i
) {
287 collector
.push(token
);
288 sections
.push(token
);
289 collector
= token
[4] = [];
292 section
= sections
.pop();
293 section
[5] = token
[2];
294 collector
= sections
.length
> 0 ? sections
[sections
.length
- 1][4] : nestedTokens
;
297 collector
.push(token
);
305 * A simple string scanner that is used by the template parser to find
306 * tokens in template strings.
308 function Scanner (string
) {
309 this.string
= string
;
315 * Returns `true` if the tail is empty (end of string).
317 Scanner
.prototype.eos
= function eos () {
318 return this.tail
=== '';
322 * Tries to match the given regular expression at the current position.
323 * Returns the matched text if it can match, the empty string otherwise.
325 Scanner
.prototype.scan
= function scan (re
) {
326 var match
= this.tail
.match(re
);
328 if (!match
|| match
.index
!== 0)
331 var string
= match
[0];
333 this.tail
= this.tail
.substring(string
.length
);
334 this.pos
+= string
.length
;
340 * Skips all text until the given regular expression can be matched. Returns
341 * the skipped string, which is the entire tail if no match can be made.
343 Scanner
.prototype.scanUntil
= function scanUntil (re
) {
344 var index
= this.tail
.search(re
), match
;
355 match
= this.tail
.substring(0, index
);
356 this.tail
= this.tail
.substring(index
);
359 this.pos
+= match
.length
;
365 * Represents a rendering context by wrapping a view object and
366 * maintaining a reference to the parent context.
368 function Context (view
, parentContext
) {
370 this.cache
= { '.': this.view
};
371 this.parent
= parentContext
;
375 * Creates a new context using the given view with this context
378 Context
.prototype.push
= function push (view
) {
379 return new Context(view
, this);
383 * Returns the value of the given name in this context, traversing
384 * up the context hierarchy if the value is absent in this context's view.
386 Context
.prototype.lookup
= function lookup (name
) {
387 var cache
= this.cache
;
390 if (cache
.hasOwnProperty(name
)) {
393 var context
= this, intermediateValue
, names
, index
, lookupHit
= false;
396 if (name
.indexOf('.') > 0) {
397 intermediateValue
= context
.view
;
398 names
= name
.split('.');
402 * Using the dot notion path in `name`, we descend through the
405 * To be certain that the lookup has been successful, we have to
406 * check if the last object in the path actually has the property
407 * we are looking for. We store the result in `lookupHit`.
409 * This is specially necessary for when the value has been set to
410 * `undefined` and we want to avoid looking up parent contexts.
412 * In the case where dot notation is used, we consider the lookup
413 * to be successful even if the last "object" in the path is
414 * not actually an object but a primitive (e.g., a string, or an
415 * integer), because it is sometimes useful to access a property
416 * of an autoboxed primitive, such as the length of a string.
418 while (intermediateValue
!= null && index
< names
.length
) {
419 if (index
=== names
.length
- 1)
421 hasProperty(intermediateValue
, names
[index
])
422 || primitiveHasOwnProperty(intermediateValue
, names
[index
])
425 intermediateValue
= intermediateValue
[names
[index
++]];
428 intermediateValue
= context
.view
[name
];
431 * Only checking against `hasProperty`, which always returns `false` if
432 * `context.view` is not an object. Deliberately omitting the check
433 * against `primitiveHasOwnProperty` if dot notation is not used.
435 * Consider this example:
437 * Mustache.render("The length of a football field is {{#length}}{{length}}{{/length}}.", {length: "100 yards"})
440 * If we were to check also against `primitiveHasOwnProperty`, as we do
441 * in the dot notation case, then render call would return:
443 * "The length of a football field is 9."
445 * rather than the expected:
447 * "The length of a football field is 100 yards."
449 lookupHit
= hasProperty(context
.view
, name
);
453 value
= intermediateValue
;
457 context
= context
.parent
;
463 if (isFunction(value
))
464 value
= value
.call(this.view
);
470 * A Writer knows how to take a stream of tokens and render them to a
471 * string, given a context. It also maintains a cache of templates to
472 * avoid the need to parse the same template twice.
479 * Clears all cached templates in this writer.
481 Writer
.prototype.clearCache
= function clearCache () {
486 * Parses and caches the given `template` according to the given `tags` or
487 * `mustache.tags` if `tags` is omitted, and returns the array of tokens
488 * that is generated from the parse.
490 Writer
.prototype.parse
= function parse (template
, tags
) {
491 var cache
= this.cache
;
492 var cacheKey
= template
+ ':' + (tags
|| mustache
.tags
).join(':');
493 var tokens
= cache
[cacheKey
];
496 tokens
= cache
[cacheKey
] = parseTemplate(template
, tags
);
502 * High-level method that is used to render the given `template` with
505 * The optional `partials` argument may be an object that contains the
506 * names and templates of partials that are used in the template. It may
507 * also be a function that is used to load partial templates on the fly
508 * that takes a single argument: the name of the partial.
510 * If the optional `tags` argument is given here it must be an array with two
511 * string values: the opening and closing tags used in the template (e.g.
512 * [ "<%", "%>" ]). The default is to mustache.tags.
514 Writer
.prototype.render
= function render (template
, view
, partials
, tags
) {
515 var tokens
= this.parse(template
, tags
);
516 var context
= (view
instanceof Context
) ? view
: new Context(view
);
517 return this.renderTokens(tokens
, context
, partials
, template
, tags
);
521 * Low-level method that renders the given array of `tokens` using
522 * the given `context` and `partials`.
524 * Note: The `originalTemplate` is only ever used to extract the portion
525 * of the original template that was contained in a higher-order section.
526 * If the template doesn't use higher-order sections, this argument may
529 Writer
.prototype.renderTokens
= function renderTokens (tokens
, context
, partials
, originalTemplate
, tags
) {
532 var token
, symbol
, value
;
533 for (var i
= 0, numTokens
= tokens
.length
; i
< numTokens
; ++i
) {
538 if (symbol
=== '#') value
= this.renderSection(token
, context
, partials
, originalTemplate
);
539 else if (symbol
=== '^') value
= this.renderInverted(token
, context
, partials
, originalTemplate
);
540 else if (symbol
=== '>') value
= this.renderPartial(token
, context
, partials
, tags
);
541 else if (symbol
=== '&') value
= this.unescapedValue(token
, context
);
542 else if (symbol
=== 'name') value
= this.escapedValue(token
, context
);
543 else if (symbol
=== 'text') value
= this.rawValue(token
);
545 if (value
!== undefined)
552 Writer
.prototype.renderSection
= function renderSection (token
, context
, partials
, originalTemplate
) {
555 var value
= context
.lookup(token
[1]);
557 // This function is used to render an arbitrary template
558 // in the current context by higher-order sections.
559 function subRender (template
) {
560 return self
.render(template
, context
, partials
);
565 if (isArray(value
)) {
566 for (var j
= 0, valueLength
= value
.length
; j
< valueLength
; ++j
) {
567 buffer
+= this.renderTokens(token
[4], context
.push(value
[j
]), partials
, originalTemplate
);
569 } else if (typeof value
=== 'object' || typeof value
=== 'string' || typeof value
=== 'number') {
570 buffer
+= this.renderTokens(token
[4], context
.push(value
), partials
, originalTemplate
);
571 } else if (isFunction(value
)) {
572 if (typeof originalTemplate
!== 'string')
573 throw new Error('Cannot use higher-order sections without the original template');
575 // Extract the portion of the original template that the section contains.
576 value
= value
.call(context
.view
, originalTemplate
.slice(token
[3], token
[5]), subRender
);
581 buffer
+= this.renderTokens(token
[4], context
, partials
, originalTemplate
);
586 Writer
.prototype.renderInverted
= function renderInverted (token
, context
, partials
, originalTemplate
) {
587 var value
= context
.lookup(token
[1]);
589 // Use JavaScript's definition of falsy. Include empty arrays.
590 // See https://github.com/janl/mustache.js/issues/186
591 if (!value
|| (isArray(value
) && value
.length
=== 0))
592 return this.renderTokens(token
[4], context
, partials
, originalTemplate
);
595 Writer
.prototype.renderPartial
= function renderPartial (token
, context
, partials
, tags
) {
596 if (!partials
) return;
598 var value
= isFunction(partials
) ? partials(token
[1]) : partials
[token
[1]];
600 return this.renderTokens(this.parse(value
, tags
), context
, partials
, value
);
603 Writer
.prototype.unescapedValue
= function unescapedValue (token
, context
) {
604 var value
= context
.lookup(token
[1]);
609 Writer
.prototype.escapedValue
= function escapedValue (token
, context
) {
610 var value
= context
.lookup(token
[1]);
612 return mustache
.escape(value
);
615 Writer
.prototype.rawValue
= function rawValue (token
) {
619 mustache
.name
= 'mustache.js';
620 mustache
.version
= '3.0.1';
621 mustache
.tags
= [ '{{', '}}' ];
623 // All high-level mustache.* functions use this writer.
624 var defaultWriter
= new Writer();
627 * Clears all cached templates in the default writer.
629 mustache
.clearCache
= function clearCache () {
630 return defaultWriter
.clearCache();
634 * Parses and caches the given template in the default writer and returns the
635 * array of tokens it contains. Doing this ahead of time avoids the need to
636 * parse templates on the fly as they are rendered.
638 mustache
.parse
= function parse (template
, tags
) {
639 return defaultWriter
.parse(template
, tags
);
643 * Renders the `template` with the given `view` and `partials` using the
644 * default writer. If the optional `tags` argument is given here it must be an
645 * array with two string values: the opening and closing tags used in the
646 * template (e.g. [ "<%", "%>" ]). The default is to mustache.tags.
648 mustache
.render
= function render (template
, view
, partials
, tags
) {
649 if (typeof template
!== 'string') {
650 throw new TypeError('Invalid template! Template should be a "string" ' +
651 'but "' + typeStr(template
) + '" was given as the first ' +
652 'argument for mustache#render(template, view, partials)');
655 return defaultWriter
.render(template
, view
, partials
, tags
);
658 // This is here for backwards compatibility with 0.4.x.,
659 /*eslint-disable */ // eslint wants camel cased function name
660 mustache
.to_html
= function to_html (template
, view
, partials
, send
) {
663 var result
= mustache
.render(template
, view
, partials
);
665 if (isFunction(send
)) {
672 // Export the escaping function so that the user may override it.
673 // See https://github.com/janl/mustache.js/issues/244
674 mustache
.escape
= escapeHtml
;
676 // Export these mainly for testing, but also for advanced usage.
677 mustache
.Scanner
= Scanner
;
678 mustache
.Context
= Context
;
679 mustache
.Writer
= Writer
;