3 // Copyright (c) 2009 Chris Wanstrath (Ruby)
4 // Copyright (c) 2010-2014 Jan Lehnardt (JavaScript)
5 // Copyright (c) 2010-2015 The mustache.js community
7 // Permission is hereby granted, free of charge, to any person obtaining
8 // a copy of this software and associated documentation files (the
9 // "Software"), to deal in the Software without restriction, including
10 // without limitation the rights to use, copy, modify, merge, publish,
11 // distribute, sublicense, and/or sell copies of the Software, and to
12 // permit persons to whom the Software is furnished to do so, subject to
13 // the following conditions:
15 // The above copyright notice and this permission notice shall be
16 // included in all copies or substantial portions of the Software.
18 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21 // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22 // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 // Description of import into Moodle:
28 // Checkout from https://github.com/moodle/custom-mustache.js
29 // Rebase onto latest release tag from https://github.com/janl/mustache.js
30 // Copy mustache.js into lib/amd/src/ in Moodle folder.
31 // Add the license as a comment to the file and these instructions.
32 // Add jshint tags so this file is not linted.
33 // Remove the "global define:" comment (hint for linter)
34 // Make sure that you have not removed the custom code for '$' and '<'.
37 * mustache.js - Logic-less {{mustache}} templates with JavaScript
38 * http://github.com/janl/mustache.js
41 /* jshint ignore:start */
43 (function defineMustache (global, factory) {
44 if (typeof exports === 'object' && exports && typeof exports.nodeName !== 'string') {
45 factory(exports); // CommonJS
46 } else if (typeof define === 'function' && define.amd) {
47 define(['exports'], factory); // AMD
50 factory(global.Mustache); // script, wsh, asp
52 }(this, function mustacheFactory (mustache) {
54 var objectToString = Object.prototype.toString;
55 var isArray = Array.isArray || function isArrayPolyfill (object) {
56 return objectToString.call(object) === '[object Array]';
59 function isFunction (object) {
60 return typeof object === 'function';
64 * More correct typeof string handling array
65 * which normally returns typeof 'object'
67 function typeStr (obj) {
68 return isArray(obj) ? 'array' : typeof obj;
71 function escapeRegExp (string) {
72 return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
76 * Null safe way of checking whether or not an object,
77 * including its prototype, has a given property
79 function hasProperty (obj, propName) {
80 return obj != null && typeof obj === 'object' && (propName in obj);
83 // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
84 // See https://github.com/janl/mustache.js/issues/189
85 var regExpTest = RegExp.prototype.test;
86 function testRegExp (re, string) {
87 return regExpTest.call(re, string);
90 var nonSpaceRe = /\S/;
91 function isWhitespace (string) {
92 return !testRegExp(nonSpaceRe, string);
106 function escapeHtml (string) {
107 return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap (s) {
114 var equalsRe = /\s*=/;
115 var curlyRe = /\s*\}/;
116 var tagRe = /#|\^|\/|>|\{|&|=|!|\$|</;
119 * Breaks up the given `template` string into a tree of tokens. If the `tags`
120 * argument is given here it must be an array with two string values: the
121 * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
122 * course, the default is to use mustaches (i.e. mustache.tags).
124 * A token is an array with at least 4 elements. The first element is the
125 * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
126 * did not contain a symbol (i.e. {{myValue}}) this element is "name". For
127 * all text that appears outside a symbol this element is "text".
129 * The second element of a token is its "value". For mustache tags this is
130 * whatever else was inside the tag besides the opening symbol. For text tokens
131 * this is the text itself.
133 * The third and fourth elements of the token are the start and end indices,
134 * respectively, of the token in the original template.
136 * Tokens that are the root node of a subtree contain two more elements: 1) an
137 * array of tokens in the subtree and 2) the index in the original template at
138 * which the closing tag for that section begins.
140 function parseTemplate (template, tags) {
144 var sections = []; // Stack to hold section tokens
145 var tokens = []; // Buffer to hold the tokens
146 var spaces = []; // Indices of whitespace tokens on the current line
147 var hasTag = false; // Is there a {{tag}} on the current line?
148 var nonSpace = false; // Is there a non-space char on the current line?
150 // Strips all whitespace tokens array for the current line
151 // if there was a {{#tag}} on it and otherwise only space.
152 function stripSpace () {
153 if (hasTag && !nonSpace) {
154 while (spaces.length)
155 delete tokens[spaces.pop()];
164 var openingTagRe, closingTagRe, closingCurlyRe;
165 function compileTags (tagsToCompile) {
166 if (typeof tagsToCompile === 'string')
167 tagsToCompile = tagsToCompile.split(spaceRe, 2);
169 if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)
170 throw new Error('Invalid tags: ' + tagsToCompile);
172 openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*');
173 closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1]));
174 closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1]));
177 compileTags(tags || mustache.tags);
179 var scanner = new Scanner(template);
181 var start, type, value, chr, token, openSection;
182 while (!scanner.eos()) {
185 // Match any text between tags.
186 value = scanner.scanUntil(openingTagRe);
189 for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
190 chr = value.charAt(i);
192 if (isWhitespace(chr)) {
193 spaces.push(tokens.length);
198 tokens.push([ 'text', chr, start, start + 1 ]);
201 // Check for whitespace on the current line.
207 // Match the opening tag.
208 if (!scanner.scan(openingTagRe))
214 type = scanner.scan(tagRe) || 'name';
215 scanner.scan(whiteRe);
217 // Get the tag value.
219 value = scanner.scanUntil(equalsRe);
220 scanner.scan(equalsRe);
221 scanner.scanUntil(closingTagRe);
222 } else if (type === '{') {
223 value = scanner.scanUntil(closingCurlyRe);
224 scanner.scan(curlyRe);
225 scanner.scanUntil(closingTagRe);
228 value = scanner.scanUntil(closingTagRe);
231 // Match the closing tag.
232 if (!scanner.scan(closingTagRe))
233 throw new Error('Unclosed tag at ' + scanner.pos);
235 token = [ type, value, start, scanner.pos ];
238 if (type === '#' || type === '^' || type === '$' || type === '<') {
239 sections.push(token);
240 } else if (type === '/') {
241 // Check section nesting.
242 openSection = sections.pop();
245 throw new Error('Unopened section "' + value + '" at ' + start);
247 if (openSection[1] !== value)
248 throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
249 } else if (type === 'name' || type === '{' || type === '&') {
251 } else if (type === '=') {
252 // Set the tags for the next time around.
257 // Make sure there are no open sections when we're done.
258 openSection = sections.pop();
261 throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
263 return nestTokens(squashTokens(tokens));
267 * Combines the values of consecutive text tokens in the given `tokens` array
270 function squashTokens (tokens) {
271 var squashedTokens = [];
273 var token, lastToken;
274 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
278 if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
279 lastToken[1] += token[1];
280 lastToken[3] = token[3];
282 squashedTokens.push(token);
288 return squashedTokens;
292 * Forms the given array of `tokens` into a nested tree structure where
293 * tokens that represent a section have two additional items: 1) an array of
294 * all tokens that appear in that section and 2) the index in the original
295 * template that represents the end of that section.
297 function nestTokens (tokens) {
298 var nestedTokens = [];
299 var collector = nestedTokens;
303 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
311 collector.push(token);
312 sections.push(token);
313 collector = token[4] = [];
316 section = sections.pop();
317 section[5] = token[2];
318 collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
321 collector.push(token);
329 * A simple string scanner that is used by the template parser to find
330 * tokens in template strings.
332 function Scanner (string) {
333 this.string = string;
339 * Returns `true` if the tail is empty (end of string).
341 Scanner.prototype.eos = function eos () {
342 return this.tail === '';
346 * Tries to match the given regular expression at the current position.
347 * Returns the matched text if it can match, the empty string otherwise.
349 Scanner.prototype.scan = function scan (re) {
350 var match = this.tail.match(re);
352 if (!match || match.index !== 0)
355 var string = match[0];
357 this.tail = this.tail.substring(string.length);
358 this.pos += string.length;
364 * Skips all text until the given regular expression can be matched. Returns
365 * the skipped string, which is the entire tail if no match can be made.
367 Scanner.prototype.scanUntil = function scanUntil (re) {
368 var index = this.tail.search(re), match;
379 match = this.tail.substring(0, index);
380 this.tail = this.tail.substring(index);
383 this.pos += match.length;
389 * Represents a rendering context by wrapping a view object and
390 * maintaining a reference to the parent context.
392 function Context (view, parentContext) {
395 this.cache = { '.': this.view };
396 this.parent = parentContext;
400 * Creates a new context using the given view with this context
403 Context.prototype.push = function push (view) {
404 return new Context(view, this);
408 * Set a value in the current block context.
410 Context.prototype.setBlockVar = function set (name, value) {
411 var blocks = this.blocks;
413 blocks[name] = value;
419 * Clear all current block vars.
421 Context.prototype.clearBlockVars = function clearBlockVars () {
426 * Get a value only from the current block context.
428 Context.prototype.getBlockVar = function getBlockVar (name) {
429 var blocks = this.blocks;
432 if (blocks.hasOwnProperty(name)) {
433 value = blocks[name];
436 value = this.parent.getBlockVar(name);
439 // Can return undefined.
444 * Returns the value of the given name in this context, traversing
445 * up the context hierarchy if the value is absent in this context's view.
447 Context.prototype.lookup = function lookup (name) {
448 var cache = this.cache;
451 if (cache.hasOwnProperty(name)) {
454 var context = this, names, index, lookupHit = false;
457 if (name.indexOf('.') > 0) {
458 value = context.view;
459 names = name.split('.');
463 * Using the dot notion path in `name`, we descend through the
466 * To be certain that the lookup has been successful, we have to
467 * check if the last object in the path actually has the property
468 * we are looking for. We store the result in `lookupHit`.
470 * This is specially necessary for when the value has been set to
471 * `undefined` and we want to avoid looking up parent contexts.
473 while (value != null && index < names.length) {
474 if (index === names.length - 1)
475 lookupHit = hasProperty(value, names[index]);
477 value = value[names[index++]];
480 value = context.view[name];
481 lookupHit = hasProperty(context.view, name);
487 context = context.parent;
493 if (isFunction(value))
494 value = value.call(this.view);
500 * A Writer knows how to take a stream of tokens and render them to a
501 * string, given a context. It also maintains a cache of templates to
502 * avoid the need to parse the same template twice.
509 * Clears all cached templates in this writer.
511 Writer.prototype.clearCache = function clearCache () {
516 * Parses and caches the given `template` and returns the array of tokens
517 * that is generated from the parse.
519 Writer.prototype.parse = function parse (template, tags) {
520 var cache = this.cache;
521 var tokens = cache[template];
524 tokens = cache[template + ':' + (tags || mustache.tags).join(':')] = parseTemplate(template, tags);
530 * High-level method that is used to render the given `template` with
533 * The optional `partials` argument may be an object that contains the
534 * names and templates of partials that are used in the template. It may
535 * also be a function that is used to load partial templates on the fly
536 * that takes a single argument: the name of the partial.
538 Writer.prototype.render = function render (template, view, partials) {
539 var tokens = this.parse(template);
540 var context = (view instanceof Context) ? view : new Context(view);
541 return this.renderTokens(tokens, context, partials, template);
545 * Low-level method that renders the given array of `tokens` using
546 * the given `context` and `partials`.
548 * Note: The `originalTemplate` is only ever used to extract the portion
549 * of the original template that was contained in a higher-order section.
550 * If the template doesn't use higher-order sections, this argument may
553 Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate) {
556 var token, symbol, value;
557 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
562 if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate);
563 else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate);
564 else if (symbol === '>') value = this.renderPartial(token, context, partials, originalTemplate);
565 else if (symbol === '<') value = this.renderBlock(token, context, partials, originalTemplate);
566 else if (symbol === '$') value = this.renderBlockVariable(token, context, partials, originalTemplate);
567 else if (symbol === '&') value = this.unescapedValue(token, context);
568 else if (symbol === 'name') value = this.escapedValue(token, context);
569 else if (symbol === 'text') value = this.rawValue(token);
571 if (value !== undefined)
578 Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate) {
581 var value = context.lookup(token[1]);
583 // This function is used to render an arbitrary template
584 // in the current context by higher-order sections.
585 function subRender (template) {
586 return self.render(template, context, partials);
591 if (isArray(value)) {
592 for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
593 buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
595 } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
596 buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
597 } else if (isFunction(value)) {
598 if (typeof originalTemplate !== 'string')
599 throw new Error('Cannot use higher-order sections without the original template');
601 // Extract the portion of the original template that the section contains.
602 value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
607 buffer += this.renderTokens(token[4], context, partials, originalTemplate);
612 Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate) {
613 var value = context.lookup(token[1]);
615 // Use JavaScript's definition of falsy. Include empty arrays.
616 // See https://github.com/janl/mustache.js/issues/186
617 if (!value || (isArray(value) && value.length === 0))
618 return this.renderTokens(token[4], context, partials, originalTemplate);
621 Writer.prototype.renderPartial = function renderPartial (token, context, partials) {
622 if (!partials) return;
624 var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
626 return this.renderTokens(this.parse(value), context, partials, value);
629 Writer.prototype.renderBlock = function renderBlock (token, context, partials, originalTemplate) {
630 if (!partials) return;
632 var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
634 // Ignore any wrongly set block vars before we started.
635 context.clearBlockVars();
636 // We are only rendering to record the default block variables.
637 this.renderTokens(token[4], context, partials, originalTemplate);
638 // Now we render and return the result.
639 var result = this.renderTokens(this.parse(value), context, partials, value);
640 // Don't leak the block variables outside this include.
641 context.clearBlockVars();
645 Writer.prototype.renderBlockVariable = function renderBlockVariable (token, context, partials, originalTemplate) {
646 var value = token[1];
648 var exists = context.getBlockVar(value);
650 context.setBlockVar(value, originalTemplate.slice(token[3], token[5]));
651 return this.renderTokens(token[4], context, partials, originalTemplate);
653 return this.renderTokens(this.parse(exists), context, partials, exists);
657 Writer.prototype.unescapedValue = function unescapedValue (token, context) {
658 var value = context.lookup(token[1]);
663 Writer.prototype.escapedValue = function escapedValue (token, context) {
664 var value = context.lookup(token[1]);
666 return mustache.escape(value);
669 Writer.prototype.rawValue = function rawValue (token) {
673 mustache.name = 'mustache.js';
674 mustache.version = '2.3.0';
675 mustache.tags = [ '{{', '}}' ];
677 // All high-level mustache.* functions use this writer.
678 var defaultWriter = new Writer();
681 * Clears all cached templates in the default writer.
683 mustache.clearCache = function clearCache () {
684 return defaultWriter.clearCache();
688 * Parses and caches the given template in the default writer and returns the
689 * array of tokens it contains. Doing this ahead of time avoids the need to
690 * parse templates on the fly as they are rendered.
692 mustache.parse = function parse (template, tags) {
693 return defaultWriter.parse(template, tags);
697 * Renders the `template` with the given `view` and `partials` using the
700 mustache.render = function render (template, view, partials) {
701 if (typeof template !== 'string') {
702 throw new TypeError('Invalid template! Template should be a "string" ' +
703 'but "' + typeStr(template) + '" was given as the first ' +
704 'argument for mustache#render(template, view, partials)');
707 return defaultWriter.render(template, view, partials);
710 // This is here for backwards compatibility with 0.4.x.,
711 /*eslint-disable */ // eslint wants camel cased function name
712 mustache.to_html = function to_html (template, view, partials, send) {
715 var result = mustache.render(template, view, partials);
717 if (isFunction(send)) {
724 // Export the escaping function so that the user may override it.
725 // See https://github.com/janl/mustache.js/issues/244
726 mustache.escape = escapeHtml;
728 // Export these mainly for testing, but also for advanced usage.
729 mustache.Scanner = Scanner;
730 mustache.Context = Context;
731 mustache.Writer = Writer;
735 /* jshint ignore:end */