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 Branch: LAMBDA_ARGS (see note below)
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 // Make sure that you have not removed the custom code for '$' and '<'.
35 // Check if pull request from branch lambdaUpgrade420 has been accepted
36 // by moodle/custom-mustache.js repo. If not, create one and use lambdaUpgrade420
37 // as your branch in place of LAMBDA_ARGS.
40 * mustache.js - Logic-less {{mustache}} templates with JavaScript
41 * http://github.com/janl/mustache.js
44 var objectToString = Object.prototype.toString;
45 var isArray = Array.isArray || function isArrayPolyfill (object) {
46 return objectToString.call(object) === '[object Array]';
49 function isFunction (object) {
50 return typeof object === 'function';
54 * More correct typeof string handling array
55 * which normally returns typeof 'object'
57 function typeStr (obj) {
58 return isArray(obj) ? 'array' : typeof obj;
61 function escapeRegExp (string) {
62 return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
66 * Null safe way of checking whether or not an object,
67 * including its prototype, has a given property
69 function hasProperty (obj, propName) {
70 return obj != null && typeof obj === 'object' && (propName in obj);
74 * Safe way of detecting whether or not the given thing is a primitive and
75 * whether it has the given property
77 function primitiveHasOwnProperty (primitive, propName) {
80 && typeof primitive !== 'object'
81 && primitive.hasOwnProperty
82 && primitive.hasOwnProperty(propName)
86 // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
87 // See https://github.com/janl/mustache.js/issues/189
88 var regExpTest = RegExp.prototype.test;
89 function testRegExp (re, string) {
90 return regExpTest.call(re, string);
93 var nonSpaceRe = /\S/;
94 function isWhitespace (string) {
95 return !testRegExp(nonSpaceRe, string);
109 function escapeHtml (string) {
110 return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap (s) {
117 var equalsRe = /\s*=/;
118 var curlyRe = /\s*\}/;
119 var tagRe = /#|\^|\/|>|\{|&|=|!|\$|</;
122 * Breaks up the given `template` string into a tree of tokens. If the `tags`
123 * argument is given here it must be an array with two string values: the
124 * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
125 * course, the default is to use mustaches (i.e. mustache.tags).
127 * A token is an array with at least 4 elements. The first element is the
128 * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
129 * did not contain a symbol (i.e. {{myValue}}) this element is "name". For
130 * all text that appears outside a symbol this element is "text".
132 * The second element of a token is its "value". For mustache tags this is
133 * whatever else was inside the tag besides the opening symbol. For text tokens
134 * this is the text itself.
136 * The third and fourth elements of the token are the start and end indices,
137 * respectively, of the token in the original template.
139 * Tokens that are the root node of a subtree contain two more elements: 1) an
140 * array of tokens in the subtree and 2) the index in the original template at
141 * which the closing tag for that section begins.
143 * Tokens for partials also contain two more elements: 1) a string value of
144 * indendation prior to that tag and 2) the index of that tag on that line -
145 * eg a value of 2 indicates the partial is the third tag on this line.
147 function parseTemplate (template, tags) {
150 var lineHasNonSpace = false;
151 var sections = []; // Stack to hold section tokens
152 var tokens = []; // Buffer to hold the tokens
153 var spaces = []; // Indices of whitespace tokens on the current line
154 var hasTag = false; // Is there a {{tag}} on the current line?
155 var nonSpace = false; // Is there a non-space char on the current line?
156 var indentation = ''; // Tracks indentation for tags that use it
157 var tagIndex = 0; // Stores a count of number of tags encountered on a line
159 // Strips all whitespace tokens array for the current line
160 // if there was a {{#tag}} on it and otherwise only space.
161 function stripSpace () {
162 if (hasTag && !nonSpace) {
163 while (spaces.length)
164 delete tokens[spaces.pop()];
173 var openingTagRe, closingTagRe, closingCurlyRe;
174 function compileTags (tagsToCompile) {
175 if (typeof tagsToCompile === 'string')
176 tagsToCompile = tagsToCompile.split(spaceRe, 2);
178 if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)
179 throw new Error('Invalid tags: ' + tagsToCompile);
181 openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*');
182 closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1]));
183 closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1]));
186 compileTags(tags || mustache.tags);
188 var scanner = new Scanner(template);
190 var start, type, value, chr, token, openSection, tagName, endTagName;
191 while (!scanner.eos()) {
194 // Match any text between tags.
195 value = scanner.scanUntil(openingTagRe);
198 for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
199 chr = value.charAt(i);
201 if (isWhitespace(chr)) {
202 spaces.push(tokens.length);
206 lineHasNonSpace = true;
210 tokens.push([ 'text', chr, start, start + 1 ]);
213 // Check for whitespace on the current line.
218 lineHasNonSpace = false;
223 // Match the opening tag.
224 if (!scanner.scan(openingTagRe))
230 type = scanner.scan(tagRe) || 'name';
231 scanner.scan(whiteRe);
233 // Get the tag value.
235 value = scanner.scanUntil(equalsRe);
236 scanner.scan(equalsRe);
237 scanner.scanUntil(closingTagRe);
238 } else if (type === '{') {
239 value = scanner.scanUntil(closingCurlyRe);
240 scanner.scan(curlyRe);
241 scanner.scanUntil(closingTagRe);
244 value = scanner.scanUntil(closingTagRe);
247 // Match the closing tag.
248 if (!scanner.scan(closingTagRe))
249 throw new Error('Unclosed tag at ' + scanner.pos);
252 token = [ type, value, start, scanner.pos, indentation, tagIndex, lineHasNonSpace ];
254 token = [ type, value, start, scanner.pos ];
259 if (type === '#' || type === '^' || type === '$' || type === '<') {
260 sections.push(token);
261 } else if (type === '/') {
262 // Check section nesting.
263 openSection = sections.pop();
266 throw new Error('Unopened section "' + value + '" at ' + start);
267 tagName = openSection[1].split(' ', 1)[0];
268 endTagName = value.split(' ', 1)[0];
269 if (tagName !== endTagName)
270 throw new Error('Unclosed section "' + tagName + '" at ' + start);
271 } else if (type === 'name' || type === '{' || type === '&') {
273 } else if (type === '=') {
274 // Set the tags for the next time around.
281 // Make sure there are no open sections when we're done.
282 openSection = sections.pop();
285 throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
287 return nestTokens(squashTokens(tokens));
291 * Combines the values of consecutive text tokens in the given `tokens` array
294 function squashTokens (tokens) {
295 var squashedTokens = [];
297 var token, lastToken;
298 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
302 if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
303 lastToken[1] += token[1];
304 lastToken[3] = token[3];
306 squashedTokens.push(token);
312 return squashedTokens;
316 * Forms the given array of `tokens` into a nested tree structure where
317 * tokens that represent a section have two additional items: 1) an array of
318 * all tokens that appear in that section and 2) the index in the original
319 * template that represents the end of that section.
321 function nestTokens (tokens) {
322 var nestedTokens = [];
323 var collector = nestedTokens;
327 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
335 collector.push(token);
336 sections.push(token);
337 collector = token[4] = [];
340 section = sections.pop();
341 section[5] = token[2];
342 collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
345 collector.push(token);
353 * A simple string scanner that is used by the template parser to find
354 * tokens in template strings.
356 function Scanner (string) {
357 this.string = string;
363 * Returns `true` if the tail is empty (end of string).
365 Scanner.prototype.eos = function eos () {
366 return this.tail === '';
370 * Tries to match the given regular expression at the current position.
371 * Returns the matched text if it can match, the empty string otherwise.
373 Scanner.prototype.scan = function scan (re) {
374 var match = this.tail.match(re);
376 if (!match || match.index !== 0)
379 var string = match[0];
381 this.tail = this.tail.substring(string.length);
382 this.pos += string.length;
388 * Skips all text until the given regular expression can be matched. Returns
389 * the skipped string, which is the entire tail if no match can be made.
391 Scanner.prototype.scanUntil = function scanUntil (re) {
392 var index = this.tail.search(re), match;
403 match = this.tail.substring(0, index);
404 this.tail = this.tail.substring(index);
407 this.pos += match.length;
413 * Represents a rendering context by wrapping a view object and
414 * maintaining a reference to the parent context.
416 function Context (view, parentContext) {
419 this.cache = { '.': this.view };
420 this.parent = parentContext;
424 * Creates a new context using the given view with this context
427 Context.prototype.push = function push (view) {
428 return new Context(view, this);
432 * Set a value in the current block context.
434 Context.prototype.setBlockVar = function set (name, value) {
435 var blocks = this.blocks;
436 blocks[name] = value;
440 * Clear all current block vars.
442 Context.prototype.clearBlockVars = function clearBlockVars () {
446 * Get a value only from the current block context.
448 Context.prototype.getBlockVar = function getBlockVar (name) {
449 var blocks = this.blocks;
451 if (blocks.hasOwnProperty(name)) {
452 value = blocks[name];
455 value = this.parent.getBlockVar(name);
458 // Can return undefined.
463 * Parse a tag name into an array of name and arguments (space separated, quoted strings allowed).
465 Context.prototype.parseNameAndArgs = function parseNameAndArgs (name) {
466 var parts = name.split(' ');
467 var inString = false;
475 for (i = 0; i < parts.length; i++) {
480 unescapedArg = arg.replace('\\\\', '');
481 if (unescapedArg.search(/^"$|[^\\]"$/) !== -1) {
482 finalArgs[finalArgs.length] = argbuffer + ' ' + arg.substr(0, arg.length - 1);
486 argbuffer += ' ' + arg;
489 if (arg.search(/^"/) !== -1 && !first) {
490 unescapedArg = arg.replace('\\\\', '');
491 if (unescapedArg.search(/^".*[^\\]"$/) !== -1) {
492 finalArgs[finalArgs.length] = arg.substr(1, arg.length - 2);
495 argbuffer = arg.substr(1);
498 if (arg.search(/^\d+(\.\d*)?$/) !== -1) {
499 finalArgs[finalArgs.length] = parseFloat(arg);
500 } else if (arg === 'true') {
501 finalArgs[finalArgs.length] = 1;
502 } else if (arg === 'false') {
503 finalArgs[finalArgs.length] = 0;
505 finalArgs[finalArgs.length] = arg;
507 finalArgs[finalArgs.length] = this.lookup(arg);
518 * Returns the value of the given name in this context, traversing
519 * up the context hierarchy if the value is absent in this context's view.
521 Context.prototype.lookup = function lookup (name) {
522 var cache = this.cache;
523 var lambdaArgs = this.parseNameAndArgs(name);
524 name= lambdaArgs.shift();
527 if (cache.hasOwnProperty(name)) {
530 var context = this, intermediateValue, names, index, lookupHit = false;
533 if (name.indexOf('.') > 0) {
534 intermediateValue = context.view;
535 names = name.split('.');
539 * Using the dot notion path in `name`, we descend through the
542 * To be certain that the lookup has been successful, we have to
543 * check if the last object in the path actually has the property
544 * we are looking for. We store the result in `lookupHit`.
546 * This is specially necessary for when the value has been set to
547 * `undefined` and we want to avoid looking up parent contexts.
549 * In the case where dot notation is used, we consider the lookup
550 * to be successful even if the last "object" in the path is
551 * not actually an object but a primitive (e.g., a string, or an
552 * integer), because it is sometimes useful to access a property
553 * of an autoboxed primitive, such as the length of a string.
555 while (intermediateValue != null && index < names.length) {
556 if (index === names.length - 1)
558 hasProperty(intermediateValue, names[index])
559 || primitiveHasOwnProperty(intermediateValue, names[index])
562 intermediateValue = intermediateValue[names[index++]];
565 intermediateValue = context.view[name];
568 * Only checking against `hasProperty`, which always returns `false` if
569 * `context.view` is not an object. Deliberately omitting the check
570 * against `primitiveHasOwnProperty` if dot notation is not used.
572 * Consider this example:
574 * Mustache.render("The length of a football field is {{#length}}{{length}}{{/length}}.", {length: "100 yards"})
577 * If we were to check also against `primitiveHasOwnProperty`, as we do
578 * in the dot notation case, then render call would return:
580 * "The length of a football field is 9."
582 * rather than the expected:
584 * "The length of a football field is 100 yards."
586 lookupHit = hasProperty(context.view, name);
590 value = intermediateValue;
594 context = context.parent;
600 if (isFunction(value))
601 value = value.call(this.view, lambdaArgs);
607 * A Writer knows how to take a stream of tokens and render them to a
608 * string, given a context. It also maintains a cache of templates to
609 * avoid the need to parse the same template twice.
612 this.templateCache = {
614 set: function set (key, value) {
615 this._cache[key] = value;
617 get: function get (key) {
618 return this._cache[key];
620 clear: function clear () {
627 * Clears all cached templates in this writer.
629 Writer.prototype.clearCache = function clearCache () {
630 if (typeof this.templateCache !== 'undefined') {
631 this.templateCache.clear();
636 * Parses and caches the given `template` according to the given `tags` or
637 * `mustache.tags` if `tags` is omitted, and returns the array of tokens
638 * that is generated from the parse.
640 Writer.prototype.parse = function parse (template, tags) {
641 var cache = this.templateCache;
642 var cacheKey = template + ':' + (tags || mustache.tags).join(':');
643 var isCacheEnabled = typeof cache !== 'undefined';
644 var tokens = isCacheEnabled ? cache.get(cacheKey) : undefined;
646 if (tokens == undefined) {
647 tokens = parseTemplate(template, tags);
648 isCacheEnabled && cache.set(cacheKey, tokens);
654 * High-level method that is used to render the given `template` with
657 * The optional `partials` argument may be an object that contains the
658 * names and templates of partials that are used in the template. It may
659 * also be a function that is used to load partial templates on the fly
660 * that takes a single argument: the name of the partial.
662 * If the optional `config` argument is given here, then it should be an
663 * object with a `tags` attribute or an `escape` attribute or both.
664 * If an array is passed, then it will be interpreted the same way as
665 * a `tags` attribute on a `config` object.
667 * The `tags` attribute of a `config` object must be an array with two
668 * string values: the opening and closing tags used in the template (e.g.
669 * [ "<%", "%>" ]). The default is to mustache.tags.
671 * The `escape` attribute of a `config` object must be a function which
672 * accepts a string as input and outputs a safely escaped string.
673 * If an `escape` function is not provided, then an HTML-safe string
674 * escaping function is used as the default.
676 Writer.prototype.render = function render (template, view, partials, config) {
677 var tags = this.getConfigTags(config);
678 var tokens = this.parse(template, tags);
679 var context = (view instanceof Context) ? view : new Context(view, undefined);
680 return this.renderTokens(tokens, context, partials, template, config);
684 * Low-level method that renders the given array of `tokens` using
685 * the given `context` and `partials`.
687 * Note: The `originalTemplate` is only ever used to extract the portion
688 * of the original template that was contained in a higher-order section.
689 * If the template doesn't use higher-order sections, this argument may
692 Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate, config) {
695 var token, symbol, value;
696 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
701 if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate, config);
702 else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate, config);
703 else if (symbol === '>') value = this.renderPartial(token, context, partials, config);
704 else if (symbol === '<') value = this.renderBlock(token, context, partials, originalTemplate, config);
705 else if (symbol === '$') value = this.renderBlockVariable(token, context, partials, originalTemplate, config);
706 else if (symbol === '&') value = this.unescapedValue(token, context);
707 else if (symbol === 'name') value = this.escapedValue(token, context, config);
708 else if (symbol === 'text') value = this.rawValue(token);
710 if (value !== undefined)
717 Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate, config) {
720 var lambdaArgs = context.parseNameAndArgs(token[1]);
721 var name = lambdaArgs.shift();
722 var value = context.lookup(name);
724 // This function is used to render an arbitrary template
725 // in the current context by higher-order sections.
726 function subRender (template) {
727 return self.render(template, context, partials, config);
732 if (isArray(value)) {
733 for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
734 buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate, config);
736 } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
737 buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate, config);
738 } else if (isFunction(value)) {
739 if (typeof originalTemplate !== 'string')
740 throw new Error('Cannot use higher-order sections without the original template');
742 // Extract the portion of the original template that the section contains.
743 value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender, lambdaArgs);
748 buffer += this.renderTokens(token[4], context, partials, originalTemplate, config);
753 Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate, config) {
754 var value = context.lookup(token[1]);
756 // Use JavaScript's definition of falsy. Include empty arrays.
757 // See https://github.com/janl/mustache.js/issues/186
758 if (!value || (isArray(value) && value.length === 0))
759 return this.renderTokens(token[4], context, partials, originalTemplate, config);
762 Writer.prototype.indentPartial = function indentPartial (partial, indentation, lineHasNonSpace) {
763 var filteredIndentation = indentation.replace(/[^ \t]/g, '');
764 var partialByNl = partial.split('\n');
765 for (var i = 0; i < partialByNl.length; i++) {
766 if (partialByNl[i].length && (i > 0 || !lineHasNonSpace)) {
767 partialByNl[i] = filteredIndentation + partialByNl[i];
770 return partialByNl.join('\n');
773 Writer.prototype.renderPartial = function renderPartial (token, context, partials, config) {
774 if (!partials) return;
775 var tags = this.getConfigTags(config);
777 var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
779 var lineHasNonSpace = token[6];
780 var tagIndex = token[5];
781 var indentation = token[4];
782 var indentedValue = value;
783 if (tagIndex == 0 && indentation) {
784 indentedValue = this.indentPartial(value, indentation, lineHasNonSpace);
786 var tokens = this.parse(indentedValue, tags);
787 return this.renderTokens(tokens, context, partials, indentedValue, config);
791 Writer.prototype.renderBlock = function renderBlock (token, context, partials, originalTemplate, config) {
792 if (!partials) return;
794 var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
796 // Ignore any wrongly set block vars before we started.
797 context.clearBlockVars();
798 // We are only rendering to record the default block variables.
799 this.renderTokens(token[4], context, partials, originalTemplate, config);
800 // Now we render and return the result.
801 var result = this.renderTokens(this.parse(value), context, partials, value, config);
802 // Don't leak the block variables outside this include.
803 context.clearBlockVars();
807 Writer.prototype.renderBlockVariable = function renderBlockVariable (token, context, partials, originalTemplate, config) {
808 var value = token[1];
810 var exists = context.getBlockVar(value);
812 context.setBlockVar(value, originalTemplate.slice(token[3], token[5]));
813 return this.renderTokens(token[4], context, partials, originalTemplate, config);
815 return this.renderTokens(this.parse(exists), context, partials, exists, config);
819 Writer.prototype.unescapedValue = function unescapedValue (token, context) {
820 var value = context.lookup(token[1]);
825 Writer.prototype.escapedValue = function escapedValue (token, context, config) {
826 var escape = this.getConfigEscape(config) || mustache.escape;
827 var value = context.lookup(token[1]);
829 return (typeof value === 'number' && escape === mustache.escape) ? String(value) : escape(value);
832 Writer.prototype.rawValue = function rawValue (token) {
836 Writer.prototype.getConfigTags = function getConfigTags (config) {
837 if (isArray(config)) {
840 else if (config && typeof config === 'object') {
848 Writer.prototype.getConfigEscape = function getConfigEscape (config) {
849 if (config && typeof config === 'object' && !isArray(config)) {
850 return config.escape;
860 tags: [ '{{', '}}' ],
861 clearCache: undefined,
869 * Allows a user to override the default caching strategy, by providing an
870 * object with set, get and clear methods. This can also be used to disable
871 * the cache by setting it to the literal `undefined`.
873 set templateCache (cache) {
874 defaultWriter.templateCache = cache;
877 * Gets the default or overridden caching object from the default writer.
879 get templateCache () {
880 return defaultWriter.templateCache;
884 // All high-level mustache.* functions use this writer.
885 var defaultWriter = new Writer();
888 * Clears all cached templates in the default writer.
890 mustache.clearCache = function clearCache () {
891 return defaultWriter.clearCache();
895 * Parses and caches the given template in the default writer and returns the
896 * array of tokens it contains. Doing this ahead of time avoids the need to
897 * parse templates on the fly as they are rendered.
899 mustache.parse = function parse (template, tags) {
900 return defaultWriter.parse(template, tags);
904 * Renders the `template` with the given `view`, `partials`, and `config`
905 * using the default writer.
907 mustache.render = function render (template, view, partials, config) {
908 if (typeof template !== 'string') {
909 throw new TypeError('Invalid template! Template should be a "string" ' +
910 'but "' + typeStr(template) + '" was given as the first ' +
911 'argument for mustache#render(template, view, partials)');
914 return defaultWriter.render(template, view, partials, config);
917 // Export the escaping function so that the user may override it.
918 // See https://github.com/janl/mustache.js/issues/244
919 mustache.escape = escapeHtml;
921 // Export these mainly for testing, but also for advanced usage.
922 mustache.Scanner = Scanner;
923 mustache.Context = Context;
924 mustache.Writer = Writer;
926 export default mustache;