Merge "Prepare for REL1_33 cut, labelling master as 1.34-alpha"
[lhc/web/wiklou.git] / resources / lib / mustache / mustache.js
1 /*!
2 * mustache.js - Logic-less {{mustache}} templates with JavaScript
3 * http://github.com/janl/mustache.js
4 */
5
6 /*global define: false Mustache: true*/
7
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
13 } else {
14 global.Mustache = {};
15 factory(global.Mustache); // script, wsh, asp
16 }
17 }(this, function mustacheFactory (mustache) {
18
19 var objectToString = Object.prototype.toString;
20 var isArray = Array.isArray || function isArrayPolyfill (object) {
21 return objectToString.call(object) === '[object Array]';
22 };
23
24 function isFunction (object) {
25 return typeof object === 'function';
26 }
27
28 /**
29 * More correct typeof string handling array
30 * which normally returns typeof 'object'
31 */
32 function typeStr (obj) {
33 return isArray(obj) ? 'array' : typeof obj;
34 }
35
36 function escapeRegExp (string) {
37 return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
38 }
39
40 /**
41 * Null safe way of checking whether or not an object,
42 * including its prototype, has a given property
43 */
44 function hasProperty (obj, propName) {
45 return obj != null && typeof obj === 'object' && (propName in obj);
46 }
47
48 /**
49 * Safe way of detecting whether or not the given thing is a primitive and
50 * whether it has the given property
51 */
52 function primitiveHasOwnProperty (primitive, propName) {
53 return (
54 primitive != null
55 && typeof primitive !== 'object'
56 && primitive.hasOwnProperty
57 && primitive.hasOwnProperty(propName)
58 );
59 }
60
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);
66 }
67
68 var nonSpaceRe = /\S/;
69 function isWhitespace (string) {
70 return !testRegExp(nonSpaceRe, string);
71 }
72
73 var entityMap = {
74 '&': '&',
75 '<': '&lt;',
76 '>': '&gt;',
77 '"': '&quot;',
78 "'": '&#39;',
79 '/': '&#x2F;',
80 '`': '&#x60;',
81 '=': '&#x3D;'
82 };
83
84 function escapeHtml (string) {
85 return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap (s) {
86 return entityMap[s];
87 });
88 }
89
90 var whiteRe = /\s*/;
91 var spaceRe = /\s+/;
92 var equalsRe = /\s*=/;
93 var curlyRe = /\s*\}/;
94 var tagRe = /#|\^|\/|>|\{|&|=|!/;
95
96 /**
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).
101 *
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".
106 *
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.
110 *
111 * The third and fourth elements of the token are the start and end indices,
112 * respectively, of the token in the original template.
113 *
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.
117 */
118 function parseTemplate (template, tags) {
119 if (!template)
120 return [];
121
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?
127
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()];
134 } else {
135 spaces = [];
136 }
137
138 hasTag = false;
139 nonSpace = false;
140 }
141
142 var openingTagRe, closingTagRe, closingCurlyRe;
143 function compileTags (tagsToCompile) {
144 if (typeof tagsToCompile === 'string')
145 tagsToCompile = tagsToCompile.split(spaceRe, 2);
146
147 if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)
148 throw new Error('Invalid tags: ' + tagsToCompile);
149
150 openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*');
151 closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1]));
152 closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1]));
153 }
154
155 compileTags(tags || mustache.tags);
156
157 var scanner = new Scanner(template);
158
159 var start, type, value, chr, token, openSection;
160 while (!scanner.eos()) {
161 start = scanner.pos;
162
163 // Match any text between tags.
164 value = scanner.scanUntil(openingTagRe);
165
166 if (value) {
167 for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
168 chr = value.charAt(i);
169
170 if (isWhitespace(chr)) {
171 spaces.push(tokens.length);
172 } else {
173 nonSpace = true;
174 }
175
176 tokens.push([ 'text', chr, start, start + 1 ]);
177 start += 1;
178
179 // Check for whitespace on the current line.
180 if (chr === '\n')
181 stripSpace();
182 }
183 }
184
185 // Match the opening tag.
186 if (!scanner.scan(openingTagRe))
187 break;
188
189 hasTag = true;
190
191 // Get the tag type.
192 type = scanner.scan(tagRe) || 'name';
193 scanner.scan(whiteRe);
194
195 // Get the tag value.
196 if (type === '=') {
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);
204 type = '&';
205 } else {
206 value = scanner.scanUntil(closingTagRe);
207 }
208
209 // Match the closing tag.
210 if (!scanner.scan(closingTagRe))
211 throw new Error('Unclosed tag at ' + scanner.pos);
212
213 token = [ type, value, start, scanner.pos ];
214 tokens.push(token);
215
216 if (type === '#' || type === '^') {
217 sections.push(token);
218 } else if (type === '/') {
219 // Check section nesting.
220 openSection = sections.pop();
221
222 if (!openSection)
223 throw new Error('Unopened section "' + value + '" at ' + start);
224
225 if (openSection[1] !== value)
226 throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
227 } else if (type === 'name' || type === '{' || type === '&') {
228 nonSpace = true;
229 } else if (type === '=') {
230 // Set the tags for the next time around.
231 compileTags(value);
232 }
233 }
234
235 // Make sure there are no open sections when we're done.
236 openSection = sections.pop();
237
238 if (openSection)
239 throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
240
241 return nestTokens(squashTokens(tokens));
242 }
243
244 /**
245 * Combines the values of consecutive text tokens in the given `tokens` array
246 * to a single token.
247 */
248 function squashTokens (tokens) {
249 var squashedTokens = [];
250
251 var token, lastToken;
252 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
253 token = tokens[i];
254
255 if (token) {
256 if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
257 lastToken[1] += token[1];
258 lastToken[3] = token[3];
259 } else {
260 squashedTokens.push(token);
261 lastToken = token;
262 }
263 }
264 }
265
266 return squashedTokens;
267 }
268
269 /**
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.
274 */
275 function nestTokens (tokens) {
276 var nestedTokens = [];
277 var collector = nestedTokens;
278 var sections = [];
279
280 var token, section;
281 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
282 token = tokens[i];
283
284 switch (token[0]) {
285 case '#':
286 case '^':
287 collector.push(token);
288 sections.push(token);
289 collector = token[4] = [];
290 break;
291 case '/':
292 section = sections.pop();
293 section[5] = token[2];
294 collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
295 break;
296 default:
297 collector.push(token);
298 }
299 }
300
301 return nestedTokens;
302 }
303
304 /**
305 * A simple string scanner that is used by the template parser to find
306 * tokens in template strings.
307 */
308 function Scanner (string) {
309 this.string = string;
310 this.tail = string;
311 this.pos = 0;
312 }
313
314 /**
315 * Returns `true` if the tail is empty (end of string).
316 */
317 Scanner.prototype.eos = function eos () {
318 return this.tail === '';
319 };
320
321 /**
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.
324 */
325 Scanner.prototype.scan = function scan (re) {
326 var match = this.tail.match(re);
327
328 if (!match || match.index !== 0)
329 return '';
330
331 var string = match[0];
332
333 this.tail = this.tail.substring(string.length);
334 this.pos += string.length;
335
336 return string;
337 };
338
339 /**
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.
342 */
343 Scanner.prototype.scanUntil = function scanUntil (re) {
344 var index = this.tail.search(re), match;
345
346 switch (index) {
347 case -1:
348 match = this.tail;
349 this.tail = '';
350 break;
351 case 0:
352 match = '';
353 break;
354 default:
355 match = this.tail.substring(0, index);
356 this.tail = this.tail.substring(index);
357 }
358
359 this.pos += match.length;
360
361 return match;
362 };
363
364 /**
365 * Represents a rendering context by wrapping a view object and
366 * maintaining a reference to the parent context.
367 */
368 function Context (view, parentContext) {
369 this.view = view;
370 this.cache = { '.': this.view };
371 this.parent = parentContext;
372 }
373
374 /**
375 * Creates a new context using the given view with this context
376 * as the parent.
377 */
378 Context.prototype.push = function push (view) {
379 return new Context(view, this);
380 };
381
382 /**
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.
385 */
386 Context.prototype.lookup = function lookup (name) {
387 var cache = this.cache;
388
389 var value;
390 if (cache.hasOwnProperty(name)) {
391 value = cache[name];
392 } else {
393 var context = this, intermediateValue, names, index, lookupHit = false;
394
395 while (context) {
396 if (name.indexOf('.') > 0) {
397 intermediateValue = context.view;
398 names = name.split('.');
399 index = 0;
400
401 /**
402 * Using the dot notion path in `name`, we descend through the
403 * nested objects.
404 *
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`.
408 *
409 * This is specially necessary for when the value has been set to
410 * `undefined` and we want to avoid looking up parent contexts.
411 *
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.
417 **/
418 while (intermediateValue != null && index < names.length) {
419 if (index === names.length - 1)
420 lookupHit = (
421 hasProperty(intermediateValue, names[index])
422 || primitiveHasOwnProperty(intermediateValue, names[index])
423 );
424
425 intermediateValue = intermediateValue[names[index++]];
426 }
427 } else {
428 intermediateValue = context.view[name];
429
430 /**
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.
434 *
435 * Consider this example:
436 * ```
437 * Mustache.render("The length of a football field is {{#length}}{{length}}{{/length}}.", {length: "100 yards"})
438 * ```
439 *
440 * If we were to check also against `primitiveHasOwnProperty`, as we do
441 * in the dot notation case, then render call would return:
442 *
443 * "The length of a football field is 9."
444 *
445 * rather than the expected:
446 *
447 * "The length of a football field is 100 yards."
448 **/
449 lookupHit = hasProperty(context.view, name);
450 }
451
452 if (lookupHit) {
453 value = intermediateValue;
454 break;
455 }
456
457 context = context.parent;
458 }
459
460 cache[name] = value;
461 }
462
463 if (isFunction(value))
464 value = value.call(this.view);
465
466 return value;
467 };
468
469 /**
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.
473 */
474 function Writer () {
475 this.cache = {};
476 }
477
478 /**
479 * Clears all cached templates in this writer.
480 */
481 Writer.prototype.clearCache = function clearCache () {
482 this.cache = {};
483 };
484
485 /**
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.
489 */
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];
494
495 if (tokens == null)
496 tokens = cache[cacheKey] = parseTemplate(template, tags);
497
498 return tokens;
499 };
500
501 /**
502 * High-level method that is used to render the given `template` with
503 * the given `view`.
504 *
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.
509 *
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.
513 */
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);
518 };
519
520 /**
521 * Low-level method that renders the given array of `tokens` using
522 * the given `context` and `partials`.
523 *
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
527 * be omitted.
528 */
529 Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate, tags) {
530 var buffer = '';
531
532 var token, symbol, value;
533 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
534 value = undefined;
535 token = tokens[i];
536 symbol = token[0];
537
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);
544
545 if (value !== undefined)
546 buffer += value;
547 }
548
549 return buffer;
550 };
551
552 Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate) {
553 var self = this;
554 var buffer = '';
555 var value = context.lookup(token[1]);
556
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);
561 }
562
563 if (!value) return;
564
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);
568 }
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');
574
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);
577
578 if (value != null)
579 buffer += value;
580 } else {
581 buffer += this.renderTokens(token[4], context, partials, originalTemplate);
582 }
583 return buffer;
584 };
585
586 Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate) {
587 var value = context.lookup(token[1]);
588
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);
593 };
594
595 Writer.prototype.renderPartial = function renderPartial (token, context, partials, tags) {
596 if (!partials) return;
597
598 var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
599 if (value != null)
600 return this.renderTokens(this.parse(value, tags), context, partials, value);
601 };
602
603 Writer.prototype.unescapedValue = function unescapedValue (token, context) {
604 var value = context.lookup(token[1]);
605 if (value != null)
606 return value;
607 };
608
609 Writer.prototype.escapedValue = function escapedValue (token, context) {
610 var value = context.lookup(token[1]);
611 if (value != null)
612 return mustache.escape(value);
613 };
614
615 Writer.prototype.rawValue = function rawValue (token) {
616 return token[1];
617 };
618
619 mustache.name = 'mustache.js';
620 mustache.version = '3.0.1';
621 mustache.tags = [ '{{', '}}' ];
622
623 // All high-level mustache.* functions use this writer.
624 var defaultWriter = new Writer();
625
626 /**
627 * Clears all cached templates in the default writer.
628 */
629 mustache.clearCache = function clearCache () {
630 return defaultWriter.clearCache();
631 };
632
633 /**
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.
637 */
638 mustache.parse = function parse (template, tags) {
639 return defaultWriter.parse(template, tags);
640 };
641
642 /**
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.
647 */
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)');
653 }
654
655 return defaultWriter.render(template, view, partials, tags);
656 };
657
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) {
661 /*eslint-enable*/
662
663 var result = mustache.render(template, view, partials);
664
665 if (isFunction(send)) {
666 send(result);
667 } else {
668 return result;
669 }
670 };
671
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;
675
676 // Export these mainly for testing, but also for advanced usage.
677 mustache.Scanner = Scanner;
678 mustache.Context = Context;
679 mustache.Writer = Writer;
680
681 return mustache;
682 }));