0001
0002
0003
0004
0005
0006
0007
0008 (function defineMustache (global, factory) {
0009 if (typeof exports === 'object' && exports && typeof exports.nodeName !== 'string') {
0010 factory(exports);
0011 } else if (typeof define === 'function' && define.amd) {
0012 define(['exports'], factory);
0013 } else {
0014 global.Mustache = {};
0015 factory(global.Mustache);
0016 }
0017 }(this, function mustacheFactory (mustache) {
0018
0019 var objectToString = Object.prototype.toString;
0020 var isArray = Array.isArray || function isArrayPolyfill (object) {
0021 return objectToString.call(object) === '[object Array]';
0022 };
0023
0024 function isFunction (object) {
0025 return typeof object === 'function';
0026 }
0027
0028
0029
0030
0031
0032 function typeStr (obj) {
0033 return isArray(obj) ? 'array' : typeof obj;
0034 }
0035
0036 function escapeRegExp (string) {
0037 return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
0038 }
0039
0040
0041
0042
0043
0044 function hasProperty (obj, propName) {
0045 return obj != null && typeof obj === 'object' && (propName in obj);
0046 }
0047
0048
0049
0050
0051
0052 function primitiveHasOwnProperty (primitive, propName) {
0053 return (
0054 primitive != null
0055 && typeof primitive !== 'object'
0056 && primitive.hasOwnProperty
0057 && primitive.hasOwnProperty(propName)
0058 );
0059 }
0060
0061
0062
0063 var regExpTest = RegExp.prototype.test;
0064 function testRegExp (re, string) {
0065 return regExpTest.call(re, string);
0066 }
0067
0068 var nonSpaceRe = /\S/;
0069 function isWhitespace (string) {
0070 return !testRegExp(nonSpaceRe, string);
0071 }
0072
0073 var entityMap = {
0074 '&': '&',
0075 '<': '<',
0076 '>': '>',
0077 '"': '"',
0078 "'": ''',
0079 '/': '/',
0080 '`': '`',
0081 '=': '='
0082 };
0083
0084 function escapeHtml (string) {
0085 return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap (s) {
0086 return entityMap[s];
0087 });
0088 }
0089
0090 var whiteRe = /\s*/;
0091 var spaceRe = /\s+/;
0092 var equalsRe = /\s*=/;
0093 var curlyRe = /\s*\}/;
0094 var tagRe = /#|\^|\/|>|\{|&|=|!/;
0095
0096 /**
0097 * Breaks up the given `template` string into a tree of tokens. If the `tags`
0098 * argument is given here it must be an array with two string values: the
0099 * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
0100 * course, the default is to use mustaches (i.e. mustache.tags).
0101 *
0102 * A token is an array with at least 4 elements. The first element is the
0103 * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
0104 * did not contain a symbol (i.e. {{myValue}}) this element is "name". For
0105 * all text that appears outside a symbol this element is "text".
0106 *
0107 * The second element of a token is its "value". For mustache tags this is
0108 * whatever else was inside the tag besides the opening symbol. For text tokens
0109 * this is the text itself.
0110 *
0111 * The third and fourth elements of the token are the start and end indices,
0112 * respectively, of the token in the original template.
0113 *
0114 * Tokens that are the root node of a subtree contain two more elements: 1) an
0115 * array of tokens in the subtree and 2) the index in the original template at
0116 * which the closing tag for that section begins.
0117 */
0118 function parseTemplate (template, tags) {
0119 if (!template)
0120 return [];
0121
0122 var sections = []; // Stack to hold section tokens
0123 var tokens = []; // Buffer to hold the tokens
0124 var spaces = []; // Indices of whitespace tokens on the current line
0125 var hasTag = false; // Is there a {{tag}} on the current line?
0126 var nonSpace = false; // Is there a non-space char on the current line?
0127
0128 // Strips all whitespace tokens array for the current line
0129 // if there was a {{#tag}} on it and otherwise only space.
0130 function stripSpace () {
0131 if (hasTag && !nonSpace) {
0132 while (spaces.length)
0133 delete tokens[spaces.pop()];
0134 } else {
0135 spaces = [];
0136 }
0137
0138 hasTag = false;
0139 nonSpace = false;
0140 }
0141
0142 var openingTagRe, closingTagRe, closingCurlyRe;
0143 function compileTags (tagsToCompile) {
0144 if (typeof tagsToCompile === 'string')
0145 tagsToCompile = tagsToCompile.split(spaceRe, 2);
0146
0147 if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)
0148 throw new Error('Invalid tags: ' + tagsToCompile);
0149
0150 openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*');
0151 closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1]));
0152 closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1]));
0153 }
0154
0155 compileTags(tags || mustache.tags);
0156
0157 var scanner = new Scanner(template);
0158
0159 var start, type, value, chr, token, openSection;
0160 while (!scanner.eos()) {
0161 start = scanner.pos;
0162
0163 // Match any text between tags.
0164 value = scanner.scanUntil(openingTagRe);
0165
0166 if (value) {
0167 for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
0168 chr = value.charAt(i);
0169
0170 if (isWhitespace(chr)) {
0171 spaces.push(tokens.length);
0172 } else {
0173 nonSpace = true;
0174 }
0175
0176 tokens.push([ 'text', chr, start, start + 1 ]);
0177 start += 1;
0178
0179 // Check for whitespace on the current line.
0180 if (chr === '\n')
0181 stripSpace();
0182 }
0183 }
0184
0185 // Match the opening tag.
0186 if (!scanner.scan(openingTagRe))
0187 break;
0188
0189 hasTag = true;
0190
0191 // Get the tag type.
0192 type = scanner.scan(tagRe) || 'name';
0193 scanner.scan(whiteRe);
0194
0195 // Get the tag value.
0196 if (type === '=') {
0197 value = scanner.scanUntil(equalsRe);
0198 scanner.scan(equalsRe);
0199 scanner.scanUntil(closingTagRe);
0200 } else if (type === '{') {
0201 value = scanner.scanUntil(closingCurlyRe);
0202 scanner.scan(curlyRe);
0203 scanner.scanUntil(closingTagRe);
0204 type = '&';
0205 } else {
0206 value = scanner.scanUntil(closingTagRe);
0207 }
0208
0209 // Match the closing tag.
0210 if (!scanner.scan(closingTagRe))
0211 throw new Error('Unclosed tag at ' + scanner.pos);
0212
0213 token = [ type, value, start, scanner.pos ];
0214 tokens.push(token);
0215
0216 if (type === '#' || type === '^') {
0217 sections.push(token);
0218 } else if (type === '/') {
0219 // Check section nesting.
0220 openSection = sections.pop();
0221
0222 if (!openSection)
0223 throw new Error('Unopened section "' + value + '" at ' + start);
0224
0225 if (openSection[1] !== value)
0226 throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
0227 } else if (type === 'name' || type === '{' || type === '&') {
0228 nonSpace = true;
0229 } else if (type === '=') {
0230 // Set the tags for the next time around.
0231 compileTags(value);
0232 }
0233 }
0234
0235 // Make sure there are no open sections when we're done.
0236 openSection = sections.pop();
0237
0238 if (openSection)
0239 throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
0240
0241 return nestTokens(squashTokens(tokens));
0242 }
0243
0244 /**
0245 * Combines the values of consecutive text tokens in the given `tokens` array
0246 * to a single token.
0247 */
0248 function squashTokens (tokens) {
0249 var squashedTokens = [];
0250
0251 var token, lastToken;
0252 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
0253 token = tokens[i];
0254
0255 if (token) {
0256 if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
0257 lastToken[1] += token[1];
0258 lastToken[3] = token[3];
0259 } else {
0260 squashedTokens.push(token);
0261 lastToken = token;
0262 }
0263 }
0264 }
0265
0266 return squashedTokens;
0267 }
0268
0269 /**
0270 * Forms the given array of `tokens` into a nested tree structure where
0271 * tokens that represent a section have two additional items: 1) an array of
0272 * all tokens that appear in that section and 2) the index in the original
0273 * template that represents the end of that section.
0274 */
0275 function nestTokens (tokens) {
0276 var nestedTokens = [];
0277 var collector = nestedTokens;
0278 var sections = [];
0279
0280 var token, section;
0281 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
0282 token = tokens[i];
0283
0284 switch (token[0]) {
0285 case '#':
0286 case '^':
0287 collector.push(token);
0288 sections.push(token);
0289 collector = token[4] = [];
0290 break;
0291 case '/':
0292 section = sections.pop();
0293 section[5] = token[2];
0294 collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
0295 break;
0296 default:
0297 collector.push(token);
0298 }
0299 }
0300
0301 return nestedTokens;
0302 }
0303
0304 /**
0305 * A simple string scanner that is used by the template parser to find
0306 * tokens in template strings.
0307 */
0308 function Scanner (string) {
0309 this.string = string;
0310 this.tail = string;
0311 this.pos = 0;
0312 }
0313
0314 /**
0315 * Returns `true` if the tail is empty (end of string).
0316 */
0317 Scanner.prototype.eos = function eos () {
0318 return this.tail === '';
0319 };
0320
0321 /**
0322 * Tries to match the given regular expression at the current position.
0323 * Returns the matched text if it can match, the empty string otherwise.
0324 */
0325 Scanner.prototype.scan = function scan (re) {
0326 var match = this.tail.match(re);
0327
0328 if (!match || match.index !== 0)
0329 return '';
0330
0331 var string = match[0];
0332
0333 this.tail = this.tail.substring(string.length);
0334 this.pos += string.length;
0335
0336 return string;
0337 };
0338
0339 /**
0340 * Skips all text until the given regular expression can be matched. Returns
0341 * the skipped string, which is the entire tail if no match can be made.
0342 */
0343 Scanner.prototype.scanUntil = function scanUntil (re) {
0344 var index = this.tail.search(re), match;
0345
0346 switch (index) {
0347 case -1:
0348 match = this.tail;
0349 this.tail = '';
0350 break;
0351 case 0:
0352 match = '';
0353 break;
0354 default:
0355 match = this.tail.substring(0, index);
0356 this.tail = this.tail.substring(index);
0357 }
0358
0359 this.pos += match.length;
0360
0361 return match;
0362 };
0363
0364 /**
0365 * Represents a rendering context by wrapping a view object and
0366 * maintaining a reference to the parent context.
0367 */
0368 function Context (view, parentContext) {
0369 this.view = view;
0370 this.cache = { '.': this.view };
0371 this.parent = parentContext;
0372 }
0373
0374 /**
0375 * Creates a new context using the given view with this context
0376 * as the parent.
0377 */
0378 Context.prototype.push = function push (view) {
0379 return new Context(view, this);
0380 };
0381
0382 /**
0383 * Returns the value of the given name in this context, traversing
0384 * up the context hierarchy if the value is absent in this context's view.
0385 */
0386 Context.prototype.lookup = function lookup (name) {
0387 var cache = this.cache;
0388
0389 var value;
0390 if (cache.hasOwnProperty(name)) {
0391 value = cache[name];
0392 } else {
0393 var context = this, intermediateValue, names, index, lookupHit = false;
0394
0395 while (context) {
0396 if (name.indexOf('.') > 0) {
0397 intermediateValue = context.view;
0398 names = name.split('.');
0399 index = 0;
0400
0401 /**
0402 * Using the dot notion path in `name`, we descend through the
0403 * nested objects.
0404 *
0405 * To be certain that the lookup has been successful, we have to
0406 * check if the last object in the path actually has the property
0407 * we are looking for. We store the result in `lookupHit`.
0408 *
0409 * This is specially necessary for when the value has been set to
0410 * `undefined` and we want to avoid looking up parent contexts.
0411 *
0412 * In the case where dot notation is used, we consider the lookup
0413 * to be successful even if the last "object" in the path is
0414 * not actually an object but a primitive (e.g., a string, or an
0415 * integer), because it is sometimes useful to access a property
0416 * of an autoboxed primitive, such as the length of a string.
0417 **/
0418 while (intermediateValue != null && index < names.length) {
0419 if (index === names.length - 1)
0420 lookupHit = (
0421 hasProperty(intermediateValue, names[index])
0422 || primitiveHasOwnProperty(intermediateValue, names[index])
0423 );
0424
0425 intermediateValue = intermediateValue[names[index++]];
0426 }
0427 } else {
0428 intermediateValue = context.view[name];
0429
0430 /**
0431 * Only checking against `hasProperty`, which always returns `false` if
0432 * `context.view` is not an object. Deliberately omitting the check
0433 * against `primitiveHasOwnProperty` if dot notation is not used.
0434 *
0435 * Consider this example:
0436 * ```
0437 * Mustache.render("The length of a football field is {{#length}}{{length}}{{/length}}.", {length: "100 yards"})
0438 * ```
0439 *
0440 * If we were to check also against `primitiveHasOwnProperty`, as we do
0441 * in the dot notation case, then render call would return:
0442 *
0443 * "The length of a football field is 9."
0444 *
0445 * rather than the expected:
0446 *
0447 * "The length of a football field is 100 yards."
0448 **/
0449 lookupHit = hasProperty(context.view, name);
0450 }
0451
0452 if (lookupHit) {
0453 value = intermediateValue;
0454 break;
0455 }
0456
0457 context = context.parent;
0458 }
0459
0460 cache[name] = value;
0461 }
0462
0463 if (isFunction(value))
0464 value = value.call(this.view);
0465
0466 return value;
0467 };
0468
0469 /**
0470 * A Writer knows how to take a stream of tokens and render them to a
0471 * string, given a context. It also maintains a cache of templates to
0472 * avoid the need to parse the same template twice.
0473 */
0474 function Writer () {
0475 this.cache = {};
0476 }
0477
0478 /**
0479 * Clears all cached templates in this writer.
0480 */
0481 Writer.prototype.clearCache = function clearCache () {
0482 this.cache = {};
0483 };
0484
0485 /**
0486 * Parses and caches the given `template` according to the given `tags` or
0487 * `mustache.tags` if `tags` is omitted, and returns the array of tokens
0488 * that is generated from the parse.
0489 */
0490 Writer.prototype.parse = function parse (template, tags) {
0491 var cache = this.cache;
0492 var cacheKey = template + ':' + (tags || mustache.tags).join(':');
0493 var tokens = cache[cacheKey];
0494
0495 if (tokens == null)
0496 tokens = cache[cacheKey] = parseTemplate(template, tags);
0497
0498 return tokens;
0499 };
0500
0501 /**
0502 * High-level method that is used to render the given `template` with
0503 * the given `view`.
0504 *
0505 * The optional `partials` argument may be an object that contains the
0506 * names and templates of partials that are used in the template. It may
0507 * also be a function that is used to load partial templates on the fly
0508 * that takes a single argument: the name of the partial.
0509 *
0510 * If the optional `tags` argument is given here it must be an array with two
0511 * string values: the opening and closing tags used in the template (e.g.
0512 * [ "<%", "%>" ]). The default is to mustache.tags.
0513 */
0514 Writer.prototype.render = function render (template, view, partials, tags) {
0515 var tokens = this.parse(template, tags);
0516 var context = (view instanceof Context) ? view : new Context(view);
0517 return this.renderTokens(tokens, context, partials, template, tags);
0518 };
0519
0520 /**
0521 * Low-level method that renders the given array of `tokens` using
0522 * the given `context` and `partials`.
0523 *
0524 * Note: The `originalTemplate` is only ever used to extract the portion
0525 * of the original template that was contained in a higher-order section.
0526 * If the template doesn't use higher-order sections, this argument may
0527 * be omitted.
0528 */
0529 Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate, tags) {
0530 var buffer = '';
0531
0532 var token, symbol, value;
0533 for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
0534 value = undefined;
0535 token = tokens[i];
0536 symbol = token[0];
0537
0538 if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate);
0539 else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate);
0540 else if (symbol === '>') value = this.renderPartial(token, context, partials, tags);
0541 else if (symbol === '&') value = this.unescapedValue(token, context);
0542 else if (symbol === 'name') value = this.escapedValue(token, context);
0543 else if (symbol === 'text') value = this.rawValue(token);
0544
0545 if (value !== undefined)
0546 buffer += value;
0547 }
0548
0549 return buffer;
0550 };
0551
0552 Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate) {
0553 var self = this;
0554 var buffer = '';
0555 var value = context.lookup(token[1]);
0556
0557 // This function is used to render an arbitrary template
0558 // in the current context by higher-order sections.
0559 function subRender (template) {
0560 return self.render(template, context, partials);
0561 }
0562
0563 if (!value) return;
0564
0565 if (isArray(value)) {
0566 for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
0567 buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
0568 }
0569 } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
0570 buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
0571 } else if (isFunction(value)) {
0572 if (typeof originalTemplate !== 'string')
0573 throw new Error('Cannot use higher-order sections without the original template');
0574
0575 // Extract the portion of the original template that the section contains.
0576 value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
0577
0578 if (value != null)
0579 buffer += value;
0580 } else {
0581 buffer += this.renderTokens(token[4], context, partials, originalTemplate);
0582 }
0583 return buffer;
0584 };
0585
0586 Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate) {
0587 var value = context.lookup(token[1]);
0588
0589 // Use JavaScript's definition of falsy. Include empty arrays.
0590 // See https://github.com/janl/mustache.js/issues/186
0591 if (!value || (isArray(value) && value.length === 0))
0592 return this.renderTokens(token[4], context, partials, originalTemplate);
0593 };
0594
0595 Writer.prototype.renderPartial = function renderPartial (token, context, partials, tags) {
0596 if (!partials) return;
0597
0598 var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
0599 if (value != null)
0600 return this.renderTokens(this.parse(value, tags), context, partials, value);
0601 };
0602
0603 Writer.prototype.unescapedValue = function unescapedValue (token, context) {
0604 var value = context.lookup(token[1]);
0605 if (value != null)
0606 return value;
0607 };
0608
0609 Writer.prototype.escapedValue = function escapedValue (token, context) {
0610 var value = context.lookup(token[1]);
0611 if (value != null)
0612 return mustache.escape(value);
0613 };
0614
0615 Writer.prototype.rawValue = function rawValue (token) {
0616 return token[1];
0617 };
0618
0619 mustache.name = 'mustache.js';
0620 mustache.version = '3.0.1';
0621 mustache.tags = [ '{{', '}}' ];
0622
0623 // All high-level mustache.* functions use this writer.
0624 var defaultWriter = new Writer();
0625
0626 /**
0627 * Clears all cached templates in the default writer.
0628 */
0629 mustache.clearCache = function clearCache () {
0630 return defaultWriter.clearCache();
0631 };
0632
0633 /**
0634 * Parses and caches the given template in the default writer and returns the
0635 * array of tokens it contains. Doing this ahead of time avoids the need to
0636 * parse templates on the fly as they are rendered.
0637 */
0638 mustache.parse = function parse (template, tags) {
0639 return defaultWriter.parse(template, tags);
0640 };
0641
0642 /**
0643 * Renders the `template` with the given `view` and `partials` using the
0644 * default writer. If the optional `tags` argument is given here it must be an
0645 * array with two string values: the opening and closing tags used in the
0646 * template (e.g. [ "<%", "%>" ]). The default is to mustache.tags.
0647 */
0648 mustache.render = function render (template, view, partials, tags) {
0649 if (typeof template !== 'string') {
0650 throw new TypeError('Invalid template! Template should be a "string" ' +
0651 'but "' + typeStr(template) + '" was given as the first ' +
0652 'argument for mustache#render(template, view, partials)');
0653 }
0654
0655 return defaultWriter.render(template, view, partials, tags);
0656 };
0657
0658 // This is here for backwards compatibility with 0.4.x.,
0659 /*eslint-disable */ // eslint wants camel cased function name
0660 mustache.to_html = function to_html (template, view, partials, send) {
0661 /*eslint-enable*/
0662
0663 var result = mustache.render(template, view, partials);
0664
0665 if (isFunction(send)) {
0666 send(result);
0667 } else {
0668 return result;
0669 }
0670 };
0671
0672 // Export the escaping function so that the user may override it.
0673 // See https://github.com/janl/mustache.js/issues/244
0674 mustache.escape = escapeHtml;
0675
0676 // Export these mainly for testing, but also for advanced usage.
0677 mustache.Scanner = Scanner;
0678 mustache.Context = Context;
0679 mustache.Writer = Writer;
0680
0681 return mustache;
0682 }));