3 // Copyright (c) 2009 Chris Wanstrath (Ruby)
4 // Copyright (c) 2010-2014 Jan Lehnardt (JavaScript)
6 // Permission is hereby granted, free of charge, to any person obtaining
7 // a copy of this software and associated documentation files (the
8 // "Software"), to deal in the Software without restriction, including
9 // without limitation the rights to use, copy, modify, merge, publish,
10 // distribute, sublicense, and/or sell copies of the Software, and to
11 // permit persons to whom the Software is furnished to do so, subject to
12 // the following conditions:
14 // The above copyright notice and this permission notice shall be
15 // included in all copies or substantial portions of the Software.
17 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20 // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21 // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22 // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23 // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 // Description of import into Moodle:
27 // Checkout from https://github.com/moodle/custom-mustache.js
28 // Rebase onto latest release tag from https://github.com/janl/mustache.js
29 // Copy mustache.js into lib/amd/src/ in Moodle folder.
30 // Add the license as a comment to the file and these instructions.
31 // Add jshint tags so this file is not linted.
32 // Remove the "global define:" comment (hint for linter)
35 * mustache.js - Logic-less {{mustache}} templates with JavaScript
36 * http://github.com/janl/mustache.js
39 /* jshint ignore:start */
41 (function defineMustache (global, factory) {
42 if (typeof exports === 'object' && exports && typeof exports.nodeName !== 'string') {
43 factory(exports); // CommonJS
44 } else if (typeof define === 'function' && define.amd) {
45 define(['exports'], factory); // AMD
48 factory(Mustache); // script, wsh, asp
50 }(this, function mustacheFactory (mustache) {
52 var objectToString = Object.prototype.toString;
53 var isArray = Array.isArray || function isArrayPolyfill (object) {
54 return objectToString.call(object) === '[object Array]';
57 function isFunction (object) {
58 return typeof object === 'function';
62 * More correct typeof string handling array
63 * which normally returns typeof 'object'
65 function typeStr (obj) {
66 return isArray(obj) ? 'array' : typeof obj;
69 function escapeRegExp (string) {
70 return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
74 * Null safe way of checking whether or not an object,
75 * including its prototype, has a given property
77 function hasProperty (obj, propName) {
78 return obj != null && typeof obj === 'object' && (propName in obj);
81 // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
82 // See https://github.com/janl/mustache.js/issues/189
83 var regExpTest = RegExp.prototype.test;
84 function testRegExp (re, string) {
85 return regExpTest.call(re, string);
88 var nonSpaceRe = /\S/;
89 function isWhitespace (string) {
90 return !testRegExp(nonSpaceRe, string);
102 function escapeHtml (string) {
103 return String(string).replace(/[&<>"'\/]/g, function fromEntityMap (s) {
110 var equalsRe = /\s*=/;
111 var curlyRe = /\s*\}/;
112 var tagRe = /#|\^|\/|>|\{|&|=|!|\$|</;
115 * Breaks up the given `template` string into a tree of tokens. If the `tags`
116 * argument is given here it must be an array with two string values: the
117 * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
118 * course, the default is to use mustaches (i.e. mustache.tags).
120 * A token is an array with at least 4 elements. The first element is the
121 * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
122 * did not contain a symbol (i.e. {{myValue}}) this element is "name". For
123 * all text that appears outside a symbol this element is "text".
125 * The second element of a token is its "value". For mustache tags this is
126 * whatever else was inside the tag besides the opening symbol. For text tokens
127 * this is the text itself.
129 * The third and fourth elements of the token are the start and end indices,
130 * respectively, of the token in the original template.
132 * Tokens that are the root node of a subtree contain two more elements: 1) an
133 * array of tokens in the subtree and 2) the index in the original template at
134 * which the closing tag for that section begins.
136 function parseTemplate (template, tags) {
140 var sections = []; // Stack to hold section tokens
141 var tokens = []; // Buffer to hold the tokens
142 var spaces = []; // Indices of whitespace tokens on the current line
143 var hasTag = false; // Is there a {{tag}} on the current line?
144 var nonSpace = false; // Is there a non-space char on the current line?
146 // Strips all whitespace tokens array for the current line
147 // if there was a {{#tag}} on it and otherwise only space.
148 function stripSpace () {
149 if (hasTag && !nonSpace) {
150 while (spaces.length)
151 delete tokens[spaces.pop()];
160 var openingTagRe, closingTagRe, closingCurlyRe;
161 function compileTags (tagsToCompile) {
162 if (typeof tagsToCompile === 'string')
163 tagsToCompile = tagsToCompile.split(spaceRe, 2);
165 if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)
166 throw new Error('Invalid tags: ' + tagsToCompile);
168 openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*');
169 closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1]));
170 closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1]));
173 compileTags(tags || mustache.tags);
175 var scanner = new Scanner(template);
177 var start, type, value, chr, token, openSection;
178 while (!scanner.eos()) {
181 // Match any text between tags.
182 value = scanner.scanUntil(openingTagRe);
185 for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
186 chr = value.charAt(i);
188 if (isWhitespace(chr)) {
189 spaces.push(tokens.length);
194 tokens.push([ 'text', chr, start, start + 1 ]);
197 // Check for whitespace on the current line.
203 // Match the opening tag.
204 if (!scanner.scan(openingTagRe))
210 type = scanner.scan(tagRe) || 'name';
211 scanner.scan(whiteRe);
213 // Get the tag value.
215 value = scanner.scanUntil(equalsRe);
216 scanner.scan(equalsRe);
217 scanner.scanUntil(closingTagRe);
218 } else if (type === '{') {
219 value = scanner.scanUntil(closingCurlyRe);
220 scanner.scan(curlyRe);
221 scanner.scanUntil(closingTagRe);
224 value = scanner.scanUntil(closingTagRe);
227 // Match the closing tag.
228 if (!scanner.scan(closingTagRe))
229 throw new Error('Unclosed tag at ' + scanner.pos);
231 token = [ type, value, start, scanner.pos ];
234 if (type === '#' || type === '^' || type === '$' || type === '<') {
235 sections.push(token);
236 } else if (type === '/') {
237 // Check section nesting.
238 openSection = sections.pop();
241 throw new Error('Unopened section "' + value + '" at ' + start);
243 if (openSection[1] !== value)
244 throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
245 } else if (type === 'name' || type === '{' || type === '&') {
247 } else if (type === '=') {
248 // Set the tags for the next time around.
253 // Make sure there are no open sections when we're done.
254 openSection = sections.pop();
257 throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
259 return nestTokens(squashTokens(tokens));
263 * Combines the values of consecutive text tokens in the given `tokens` array
266 function squashTokens (tokens) {
267 var squashedTokens = [];
269 var token, lastToken;
270 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
274 if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
275 lastToken[1] += token[1];
276 lastToken[3] = token[3];
278 squashedTokens.push(token);
284 return squashedTokens;
288 * Forms the given array of `tokens` into a nested tree structure where
289 * tokens that represent a section have two additional items: 1) an array of
290 * all tokens that appear in that section and 2) the index in the original
291 * template that represents the end of that section.
293 function nestTokens (tokens) {
294 var nestedTokens = [];
295 var collector = nestedTokens;
299 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
307 collector.push(token);
308 sections.push(token);
309 collector = token[4] = [];
312 section = sections.pop();
313 section[5] = token[2];
314 collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
317 collector.push(token);
325 * A simple string scanner that is used by the template parser to find
326 * tokens in template strings.
328 function Scanner (string) {
329 this.string = string;
335 * Returns `true` if the tail is empty (end of string).
337 Scanner.prototype.eos = function eos () {
338 return this.tail === '';
342 * Tries to match the given regular expression at the current position.
343 * Returns the matched text if it can match, the empty string otherwise.
345 Scanner.prototype.scan = function scan (re) {
346 var match = this.tail.match(re);
348 if (!match || match.index !== 0)
351 var string = match[0];
353 this.tail = this.tail.substring(string.length);
354 this.pos += string.length;
360 * Skips all text until the given regular expression can be matched. Returns
361 * the skipped string, which is the entire tail if no match can be made.
363 Scanner.prototype.scanUntil = function scanUntil (re) {
364 var index = this.tail.search(re), match;
375 match = this.tail.substring(0, index);
376 this.tail = this.tail.substring(index);
379 this.pos += match.length;
385 * Represents a rendering context by wrapping a view object and
386 * maintaining a reference to the parent context.
388 function Context (view, parentContext) {
391 this.cache = { '.': this.view };
392 this.parent = parentContext;
396 * Creates a new context using the given view with this context
399 Context.prototype.push = function push (view) {
400 return new Context(view, this);
404 * Set a value in the current block context.
406 Context.prototype.setBlockVar = function set (name, value) {
407 var blocks = this.blocks;
409 blocks[name] = value;
415 * Clear all current block vars.
417 Context.prototype.clearBlockVars = function clearBlockVars () {
422 * Get a value only from the current block context.
424 Context.prototype.getBlockVar = function getBlockVar (name) {
425 var blocks = this.blocks;
428 if (blocks.hasOwnProperty(name)) {
429 value = blocks[name];
432 value = this.parent.getBlockVar(name);
435 // Can return undefined.
440 * Returns the value of the given name in this context, traversing
441 * up the context hierarchy if the value is absent in this context's view.
443 Context.prototype.lookup = function lookup (name) {
444 var cache = this.cache;
447 if (cache.hasOwnProperty(name)) {
450 var context = this, names, index, lookupHit = false;
453 if (name.indexOf('.') > 0) {
454 value = context.view;
455 names = name.split('.');
459 * Using the dot notion path in `name`, we descend through the
462 * To be certain that the lookup has been successful, we have to
463 * check if the last object in the path actually has the property
464 * we are looking for. We store the result in `lookupHit`.
466 * This is specially necessary for when the value has been set to
467 * `undefined` and we want to avoid looking up parent contexts.
469 while (value != null && index < names.length) {
470 if (index === names.length - 1)
471 lookupHit = hasProperty(value, names[index]);
473 value = value[names[index++]];
476 value = context.view[name];
477 lookupHit = hasProperty(context.view, name);
483 context = context.parent;
489 if (isFunction(value))
490 value = value.call(this.view);
496 * A Writer knows how to take a stream of tokens and render them to a
497 * string, given a context. It also maintains a cache of templates to
498 * avoid the need to parse the same template twice.
505 * Clears all cached templates in this writer.
507 Writer.prototype.clearCache = function clearCache () {
512 * Parses and caches the given `template` and returns the array of tokens
513 * that is generated from the parse.
515 Writer.prototype.parse = function parse (template, tags) {
516 var cache = this.cache;
517 var tokens = cache[template];
520 tokens = cache[template] = parseTemplate(template, tags);
526 * High-level method that is used to render the given `template` with
529 * The optional `partials` argument may be an object that contains the
530 * names and templates of partials that are used in the template. It may
531 * also be a function that is used to load partial templates on the fly
532 * that takes a single argument: the name of the partial.
534 Writer.prototype.render = function render (template, view, partials) {
535 var tokens = this.parse(template);
536 var context = (view instanceof Context) ? view : new Context(view);
537 return this.renderTokens(tokens, context, partials, template);
541 * Low-level method that renders the given array of `tokens` using
542 * the given `context` and `partials`.
544 * Note: The `originalTemplate` is only ever used to extract the portion
545 * of the original template that was contained in a higher-order section.
546 * If the template doesn't use higher-order sections, this argument may
549 Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate) {
552 var token, symbol, value;
553 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
558 if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate);
559 else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate);
560 else if (symbol === '>') value = this.renderPartial(token, context, partials, originalTemplate);
561 else if (symbol === '<') value = this.renderBlock(token, context, partials, originalTemplate);
562 else if (symbol === '$') value = this.renderBlockVariable(token, context, partials, originalTemplate);
563 else if (symbol === '&') value = this.unescapedValue(token, context);
564 else if (symbol === 'name') value = this.escapedValue(token, context);
565 else if (symbol === 'text') value = this.rawValue(token);
567 if (value !== undefined)
574 Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate) {
577 var value = context.lookup(token[1]);
579 // This function is used to render an arbitrary template
580 // in the current context by higher-order sections.
581 function subRender (template) {
582 return self.render(template, context, partials);
587 if (isArray(value)) {
588 for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
589 buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
591 } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
592 buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
593 } else if (isFunction(value)) {
594 if (typeof originalTemplate !== 'string')
595 throw new Error('Cannot use higher-order sections without the original template');
597 // Extract the portion of the original template that the section contains.
598 value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
603 buffer += this.renderTokens(token[4], context, partials, originalTemplate);
608 Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate) {
609 var value = context.lookup(token[1]);
611 // Use JavaScript's definition of falsy. Include empty arrays.
612 // See https://github.com/janl/mustache.js/issues/186
613 if (!value || (isArray(value) && value.length === 0))
614 return this.renderTokens(token[4], context, partials, originalTemplate);
617 Writer.prototype.renderPartial = function renderPartial (token, context, partials) {
618 if (!partials) return;
620 var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
622 return this.renderTokens(this.parse(value), context, partials, value);
625 Writer.prototype.renderBlock = function renderBlock (token, context, partials, originalTemplate) {
626 if (!partials) return;
628 var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
630 // Ignore any wrongly set block vars before we started.
631 context.clearBlockVars();
632 // We are only rendering to record the default block variables.
633 this.renderTokens(token[4], context, partials, originalTemplate);
634 // Now we render and return the result.
635 var result = this.renderTokens(this.parse(value), context, partials, value);
636 // Don't leak the block variables outside this include.
637 context.clearBlockVars();
641 Writer.prototype.renderBlockVariable = function renderBlockVariable (token, context, partials, originalTemplate) {
642 var value = token[1];
644 var exists = context.getBlockVar(value);
646 context.setBlockVar(value, originalTemplate.slice(token[3], token[5]));
647 return this.renderTokens(token[4], context, partials, originalTemplate);
649 return this.renderTokens(this.parse(exists), context, partials, exists);
653 Writer.prototype.unescapedValue = function unescapedValue (token, context) {
654 var value = context.lookup(token[1]);
659 Writer.prototype.escapedValue = function escapedValue (token, context) {
660 var value = context.lookup(token[1]);
662 return mustache.escape(value);
665 Writer.prototype.rawValue = function rawValue (token) {
669 mustache.name = 'mustache.js';
670 mustache.version = '2.1.3';
671 mustache.tags = [ '{{', '}}' ];
673 // All high-level mustache.* functions use this writer.
674 var defaultWriter = new Writer();
677 * Clears all cached templates in the default writer.
679 mustache.clearCache = function clearCache () {
680 return defaultWriter.clearCache();
684 * Parses and caches the given template in the default writer and returns the
685 * array of tokens it contains. Doing this ahead of time avoids the need to
686 * parse templates on the fly as they are rendered.
688 mustache.parse = function parse (template, tags) {
689 return defaultWriter.parse(template, tags);
693 * Renders the `template` with the given `view` and `partials` using the
696 mustache.render = function render (template, view, partials) {
697 if (typeof template !== 'string') {
698 throw new TypeError('Invalid template! Template should be a "string" ' +
699 'but "' + typeStr(template) + '" was given as the first ' +
700 'argument for mustache#render(template, view, partials)');
703 return defaultWriter.render(template, view, partials);
706 // This is here for backwards compatibility with 0.4.x.,
707 /*eslint-disable */ // eslint wants camel cased function name
708 mustache.to_html = function to_html (template, view, partials, send) {
711 var result = mustache.render(template, view, partials);
713 if (isFunction(send)) {
720 // Export the escaping function so that the user may override it.
721 // See https://github.com/janl/mustache.js/issues/244
722 mustache.escape = escapeHtml;
724 // Export these mainly for testing, but also for advanced usage.
725 mustache.Scanner = Scanner;
726 mustache.Context = Context;
727 mustache.Writer = Writer;
730 /* jshint ignore:end */