You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

719 lines
23KB

  1. /*!
  2. * mustache.js - Logic-less {{mustache}} templates with JavaScript
  3. * http://github.com/janl/mustache.js
  4. */
  5. /*global define: false Mustache: true*/
  6. (function defineMustache (global, factory) {
  7. if (typeof exports === 'object' && exports && typeof exports.nodeName !== 'string') {
  8. factory(exports); // CommonJS
  9. } else if (typeof define === 'function' && define.amd) {
  10. define(['exports'], factory); // AMD
  11. } else {
  12. global.Mustache = {};
  13. factory(global.Mustache); // script, wsh, asp
  14. }
  15. }(this, function mustacheFactory (mustache) {
  16. var objectToString = Object.prototype.toString;
  17. var isArray = Array.isArray || function isArrayPolyfill (object) {
  18. return objectToString.call(object) === '[object Array]';
  19. };
  20. function isFunction (object) {
  21. return typeof object === 'function';
  22. }
  23. /**
  24. * More correct typeof string handling array
  25. * which normally returns typeof 'object'
  26. */
  27. function typeStr (obj) {
  28. return isArray(obj) ? 'array' : typeof obj;
  29. }
  30. function escapeRegExp (string) {
  31. return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
  32. }
  33. /**
  34. * Null safe way of checking whether or not an object,
  35. * including its prototype, has a given property
  36. */
  37. function hasProperty (obj, propName) {
  38. return obj != null && typeof obj === 'object' && (propName in obj);
  39. }
  40. /**
  41. * Safe way of detecting whether or not the given thing is a primitive and
  42. * whether it has the given property
  43. */
  44. function primitiveHasOwnProperty (primitive, propName) {
  45. return (
  46. primitive != null
  47. && typeof primitive !== 'object'
  48. && primitive.hasOwnProperty
  49. && primitive.hasOwnProperty(propName)
  50. );
  51. }
  52. // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
  53. // See https://github.com/janl/mustache.js/issues/189
  54. var regExpTest = RegExp.prototype.test;
  55. function testRegExp (re, string) {
  56. return regExpTest.call(re, string);
  57. }
  58. var nonSpaceRe = /\S/;
  59. function isWhitespace (string) {
  60. return !testRegExp(nonSpaceRe, string);
  61. }
  62. var entityMap = {
  63. '&': '&',
  64. '<': '&lt;',
  65. '>': '&gt;',
  66. '"': '&quot;',
  67. "'": '&#39;',
  68. '/': '&#x2F;',
  69. '`': '&#x60;',
  70. '=': '&#x3D;'
  71. };
  72. function escapeHtml (string) {
  73. return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap (s) {
  74. return entityMap[s];
  75. });
  76. }
  77. var whiteRe = /\s*/;
  78. var spaceRe = /\s+/;
  79. var equalsRe = /\s*=/;
  80. var curlyRe = /\s*\}/;
  81. var tagRe = /#|\^|\/|>|\{|&|=|!/;
  82. /**
  83. * Breaks up the given `template` string into a tree of tokens. If the `tags`
  84. * argument is given here it must be an array with two string values: the
  85. * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
  86. * course, the default is to use mustaches (i.e. mustache.tags).
  87. *
  88. * A token is an array with at least 4 elements. The first element is the
  89. * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
  90. * did not contain a symbol (i.e. {{myValue}}) this element is "name". For
  91. * all text that appears outside a symbol this element is "text".
  92. *
  93. * The second element of a token is its "value". For mustache tags this is
  94. * whatever else was inside the tag besides the opening symbol. For text tokens
  95. * this is the text itself.
  96. *
  97. * The third and fourth elements of the token are the start and end indices,
  98. * respectively, of the token in the original template.
  99. *
  100. * Tokens that are the root node of a subtree contain two more elements: 1) an
  101. * array of tokens in the subtree and 2) the index in the original template at
  102. * which the closing tag for that section begins.
  103. *
  104. * Tokens for partials also contain two more elements: 1) a string value of
  105. * indendation prior to that tag and 2) the index of that tag on that line -
  106. * eg a value of 2 indicates the partial is the third tag on this line.
  107. */
  108. function parseTemplate (template, tags) {
  109. if (!template)
  110. return [];
  111. var sections = []; // Stack to hold section tokens
  112. var tokens = []; // Buffer to hold the tokens
  113. var spaces = []; // Indices of whitespace tokens on the current line
  114. var hasTag = false; // Is there a {{tag}} on the current line?
  115. var nonSpace = false; // Is there a non-space char on the current line?
  116. var indentation = ''; // Tracks indentation for tags that use it
  117. var tagIndex = 0; // Stores a count of number of tags encountered on a line
  118. // Strips all whitespace tokens array for the current line
  119. // if there was a {{#tag}} on it and otherwise only space.
  120. function stripSpace () {
  121. if (hasTag && !nonSpace) {
  122. while (spaces.length)
  123. delete tokens[spaces.pop()];
  124. } else {
  125. spaces = [];
  126. }
  127. hasTag = false;
  128. nonSpace = false;
  129. }
  130. var openingTagRe, closingTagRe, closingCurlyRe;
  131. function compileTags (tagsToCompile) {
  132. if (typeof tagsToCompile === 'string')
  133. tagsToCompile = tagsToCompile.split(spaceRe, 2);
  134. if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)
  135. throw new Error('Invalid tags: ' + tagsToCompile);
  136. openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*');
  137. closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1]));
  138. closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1]));
  139. }
  140. compileTags(tags || mustache.tags);
  141. var scanner = new Scanner(template);
  142. var start, type, value, chr, token, openSection;
  143. while (!scanner.eos()) {
  144. start = scanner.pos;
  145. // Match any text between tags.
  146. value = scanner.scanUntil(openingTagRe);
  147. if (value) {
  148. for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
  149. chr = value.charAt(i);
  150. if (isWhitespace(chr)) {
  151. spaces.push(tokens.length);
  152. if (!nonSpace)
  153. indentation += chr;
  154. } else {
  155. nonSpace = true;
  156. }
  157. tokens.push([ 'text', chr, start, start + 1 ]);
  158. start += 1;
  159. // Check for whitespace on the current line.
  160. if (chr === '\n') {
  161. stripSpace();
  162. indentation = '';
  163. tagIndex = 0;
  164. }
  165. }
  166. }
  167. // Match the opening tag.
  168. if (!scanner.scan(openingTagRe))
  169. break;
  170. hasTag = true;
  171. // Get the tag type.
  172. type = scanner.scan(tagRe) || 'name';
  173. scanner.scan(whiteRe);
  174. // Get the tag value.
  175. if (type === '=') {
  176. value = scanner.scanUntil(equalsRe);
  177. scanner.scan(equalsRe);
  178. scanner.scanUntil(closingTagRe);
  179. } else if (type === '{') {
  180. value = scanner.scanUntil(closingCurlyRe);
  181. scanner.scan(curlyRe);
  182. scanner.scanUntil(closingTagRe);
  183. type = '&';
  184. } else {
  185. value = scanner.scanUntil(closingTagRe);
  186. }
  187. // Match the closing tag.
  188. if (!scanner.scan(closingTagRe))
  189. throw new Error('Unclosed tag at ' + scanner.pos);
  190. if (type == '>') {
  191. token = [ type, value, start, scanner.pos, indentation, tagIndex ];
  192. } else {
  193. token = [ type, value, start, scanner.pos ];
  194. }
  195. tagIndex++;
  196. tokens.push(token);
  197. if (type === '#' || type === '^') {
  198. sections.push(token);
  199. } else if (type === '/') {
  200. // Check section nesting.
  201. openSection = sections.pop();
  202. if (!openSection)
  203. throw new Error('Unopened section "' + value + '" at ' + start);
  204. if (openSection[1] !== value)
  205. throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
  206. } else if (type === 'name' || type === '{' || type === '&') {
  207. nonSpace = true;
  208. } else if (type === '=') {
  209. // Set the tags for the next time around.
  210. compileTags(value);
  211. }
  212. }
  213. stripSpace();
  214. // Make sure there are no open sections when we're done.
  215. openSection = sections.pop();
  216. if (openSection)
  217. throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
  218. return nestTokens(squashTokens(tokens));
  219. }
  220. /**
  221. * Combines the values of consecutive text tokens in the given `tokens` array
  222. * to a single token.
  223. */
  224. function squashTokens (tokens) {
  225. var squashedTokens = [];
  226. var token, lastToken;
  227. for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
  228. token = tokens[i];
  229. if (token) {
  230. if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
  231. lastToken[1] += token[1];
  232. lastToken[3] = token[3];
  233. } else {
  234. squashedTokens.push(token);
  235. lastToken = token;
  236. }
  237. }
  238. }
  239. return squashedTokens;
  240. }
  241. /**
  242. * Forms the given array of `tokens` into a nested tree structure where
  243. * tokens that represent a section have two additional items: 1) an array of
  244. * all tokens that appear in that section and 2) the index in the original
  245. * template that represents the end of that section.
  246. */
  247. function nestTokens (tokens) {
  248. var nestedTokens = [];
  249. var collector = nestedTokens;
  250. var sections = [];
  251. var token, section;
  252. for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
  253. token = tokens[i];
  254. switch (token[0]) {
  255. case '#':
  256. case '^':
  257. collector.push(token);
  258. sections.push(token);
  259. collector = token[4] = [];
  260. break;
  261. case '/':
  262. section = sections.pop();
  263. section[5] = token[2];
  264. collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
  265. break;
  266. default:
  267. collector.push(token);
  268. }
  269. }
  270. return nestedTokens;
  271. }
  272. /**
  273. * A simple string scanner that is used by the template parser to find
  274. * tokens in template strings.
  275. */
  276. function Scanner (string) {
  277. this.string = string;
  278. this.tail = string;
  279. this.pos = 0;
  280. }
  281. /**
  282. * Returns `true` if the tail is empty (end of string).
  283. */
  284. Scanner.prototype.eos = function eos () {
  285. return this.tail === '';
  286. };
  287. /**
  288. * Tries to match the given regular expression at the current position.
  289. * Returns the matched text if it can match, the empty string otherwise.
  290. */
  291. Scanner.prototype.scan = function scan (re) {
  292. var match = this.tail.match(re);
  293. if (!match || match.index !== 0)
  294. return '';
  295. var string = match[0];
  296. this.tail = this.tail.substring(string.length);
  297. this.pos += string.length;
  298. return string;
  299. };
  300. /**
  301. * Skips all text until the given regular expression can be matched. Returns
  302. * the skipped string, which is the entire tail if no match can be made.
  303. */
  304. Scanner.prototype.scanUntil = function scanUntil (re) {
  305. var index = this.tail.search(re), match;
  306. switch (index) {
  307. case -1:
  308. match = this.tail;
  309. this.tail = '';
  310. break;
  311. case 0:
  312. match = '';
  313. break;
  314. default:
  315. match = this.tail.substring(0, index);
  316. this.tail = this.tail.substring(index);
  317. }
  318. this.pos += match.length;
  319. return match;
  320. };
  321. /**
  322. * Represents a rendering context by wrapping a view object and
  323. * maintaining a reference to the parent context.
  324. */
  325. function Context (view, parentContext) {
  326. this.view = view;
  327. this.cache = { '.': this.view };
  328. this.parent = parentContext;
  329. }
  330. /**
  331. * Creates a new context using the given view with this context
  332. * as the parent.
  333. */
  334. Context.prototype.push = function push (view) {
  335. return new Context(view, this);
  336. };
  337. /**
  338. * Returns the value of the given name in this context, traversing
  339. * up the context hierarchy if the value is absent in this context's view.
  340. */
  341. Context.prototype.lookup = function lookup (name) {
  342. var cache = this.cache;
  343. var value;
  344. if (cache.hasOwnProperty(name)) {
  345. value = cache[name];
  346. } else {
  347. var context = this, intermediateValue, names, index, lookupHit = false;
  348. while (context) {
  349. if (name.indexOf('.') > 0) {
  350. intermediateValue = context.view;
  351. names = name.split('.');
  352. index = 0;
  353. /**
  354. * Using the dot notion path in `name`, we descend through the
  355. * nested objects.
  356. *
  357. * To be certain that the lookup has been successful, we have to
  358. * check if the last object in the path actually has the property
  359. * we are looking for. We store the result in `lookupHit`.
  360. *
  361. * This is specially necessary for when the value has been set to
  362. * `undefined` and we want to avoid looking up parent contexts.
  363. *
  364. * In the case where dot notation is used, we consider the lookup
  365. * to be successful even if the last "object" in the path is
  366. * not actually an object but a primitive (e.g., a string, or an
  367. * integer), because it is sometimes useful to access a property
  368. * of an autoboxed primitive, such as the length of a string.
  369. **/
  370. while (intermediateValue != null && index < names.length) {
  371. if (index === names.length - 1)
  372. lookupHit = (
  373. hasProperty(intermediateValue, names[index])
  374. || primitiveHasOwnProperty(intermediateValue, names[index])
  375. );
  376. intermediateValue = intermediateValue[names[index++]];
  377. }
  378. } else {
  379. intermediateValue = context.view[name];
  380. /**
  381. * Only checking against `hasProperty`, which always returns `false` if
  382. * `context.view` is not an object. Deliberately omitting the check
  383. * against `primitiveHasOwnProperty` if dot notation is not used.
  384. *
  385. * Consider this example:
  386. * ```
  387. * Mustache.render("The length of a football field is {{#length}}{{length}}{{/length}}.", {length: "100 yards"})
  388. * ```
  389. *
  390. * If we were to check also against `primitiveHasOwnProperty`, as we do
  391. * in the dot notation case, then render call would return:
  392. *
  393. * "The length of a football field is 9."
  394. *
  395. * rather than the expected:
  396. *
  397. * "The length of a football field is 100 yards."
  398. **/
  399. lookupHit = hasProperty(context.view, name);
  400. }
  401. if (lookupHit) {
  402. value = intermediateValue;
  403. break;
  404. }
  405. context = context.parent;
  406. }
  407. cache[name] = value;
  408. }
  409. if (isFunction(value))
  410. value = value.call(this.view);
  411. return value;
  412. };
  413. /**
  414. * A Writer knows how to take a stream of tokens and render them to a
  415. * string, given a context. It also maintains a cache of templates to
  416. * avoid the need to parse the same template twice.
  417. */
  418. function Writer () {
  419. this.cache = {};
  420. }
  421. /**
  422. * Clears all cached templates in this writer.
  423. */
  424. Writer.prototype.clearCache = function clearCache () {
  425. this.cache = {};
  426. };
  427. /**
  428. * Parses and caches the given `template` according to the given `tags` or
  429. * `mustache.tags` if `tags` is omitted, and returns the array of tokens
  430. * that is generated from the parse.
  431. */
  432. Writer.prototype.parse = function parse (template, tags) {
  433. var cache = this.cache;
  434. var cacheKey = template + ':' + (tags || mustache.tags).join(':');
  435. var tokens = cache[cacheKey];
  436. if (tokens == null)
  437. tokens = cache[cacheKey] = parseTemplate(template, tags);
  438. return tokens;
  439. };
  440. /**
  441. * High-level method that is used to render the given `template` with
  442. * the given `view`.
  443. *
  444. * The optional `partials` argument may be an object that contains the
  445. * names and templates of partials that are used in the template. It may
  446. * also be a function that is used to load partial templates on the fly
  447. * that takes a single argument: the name of the partial.
  448. *
  449. * If the optional `tags` argument is given here it must be an array with two
  450. * string values: the opening and closing tags used in the template (e.g.
  451. * [ "<%", "%>" ]). The default is to mustache.tags.
  452. */
  453. Writer.prototype.render = function render (template, view, partials, tags) {
  454. var tokens = this.parse(template, tags);
  455. var context = (view instanceof Context) ? view : new Context(view);
  456. return this.renderTokens(tokens, context, partials, template, tags);
  457. };
  458. /**
  459. * Low-level method that renders the given array of `tokens` using
  460. * the given `context` and `partials`.
  461. *
  462. * Note: The `originalTemplate` is only ever used to extract the portion
  463. * of the original template that was contained in a higher-order section.
  464. * If the template doesn't use higher-order sections, this argument may
  465. * be omitted.
  466. */
  467. Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate, tags) {
  468. var buffer = '';
  469. var token, symbol, value;
  470. for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
  471. value = undefined;
  472. token = tokens[i];
  473. symbol = token[0];
  474. if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate);
  475. else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate);
  476. else if (symbol === '>') value = this.renderPartial(token, context, partials, tags);
  477. else if (symbol === '&') value = this.unescapedValue(token, context);
  478. else if (symbol === 'name') value = this.escapedValue(token, context);
  479. else if (symbol === 'text') value = this.rawValue(token);
  480. if (value !== undefined)
  481. buffer += value;
  482. }
  483. return buffer;
  484. };
  485. Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate) {
  486. var self = this;
  487. var buffer = '';
  488. var value = context.lookup(token[1]);
  489. // This function is used to render an arbitrary template
  490. // in the current context by higher-order sections.
  491. function subRender (template) {
  492. return self.render(template, context, partials);
  493. }
  494. if (!value) return;
  495. if (isArray(value)) {
  496. for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
  497. buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
  498. }
  499. } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
  500. buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
  501. } else if (isFunction(value)) {
  502. if (typeof originalTemplate !== 'string')
  503. throw new Error('Cannot use higher-order sections without the original template');
  504. // Extract the portion of the original template that the section contains.
  505. value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
  506. if (value != null)
  507. buffer += value;
  508. } else {
  509. buffer += this.renderTokens(token[4], context, partials, originalTemplate);
  510. }
  511. return buffer;
  512. };
  513. Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate) {
  514. var value = context.lookup(token[1]);
  515. // Use JavaScript's definition of falsy. Include empty arrays.
  516. // See https://github.com/janl/mustache.js/issues/186
  517. if (!value || (isArray(value) && value.length === 0))
  518. return this.renderTokens(token[4], context, partials, originalTemplate);
  519. };
  520. Writer.prototype.indentPartial = function indentPartial (partial, indentation) {
  521. var filteredIndentation = indentation.replace(/[^ \t]/g, '');
  522. var partialByNl = partial.split('\n');
  523. for (var i = 0; i < partialByNl.length; i++) {
  524. if (partialByNl[i].length) {
  525. partialByNl[i] = filteredIndentation + partialByNl[i];
  526. }
  527. }
  528. return partialByNl.join('\n');
  529. };
  530. Writer.prototype.renderPartial = function renderPartial (token, context, partials, tags) {
  531. if (!partials) return;
  532. var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
  533. if (value != null) {
  534. var tagIndex = token[5];
  535. var indentation = token[4];
  536. var indentedValue = value;
  537. if (tagIndex == 0 && indentation) {
  538. indentedValue = this.indentPartial(value, indentation);
  539. }
  540. return this.renderTokens(this.parse(indentedValue, tags), context, partials, value);
  541. }
  542. };
  543. Writer.prototype.unescapedValue = function unescapedValue (token, context) {
  544. var value = context.lookup(token[1]);
  545. if (value != null)
  546. return value;
  547. };
  548. Writer.prototype.escapedValue = function escapedValue (token, context) {
  549. var value = context.lookup(token[1]);
  550. if (value != null)
  551. return mustache.escape(value);
  552. };
  553. Writer.prototype.rawValue = function rawValue (token) {
  554. return token[1];
  555. };
  556. mustache.name = 'mustache.js';
  557. mustache.version = '3.0.2';
  558. mustache.tags = [ '{{', '}}' ];
  559. // All high-level mustache.* functions use this writer.
  560. var defaultWriter = new Writer();
  561. /**
  562. * Clears all cached templates in the default writer.
  563. */
  564. mustache.clearCache = function clearCache () {
  565. return defaultWriter.clearCache();
  566. };
  567. /**
  568. * Parses and caches the given template in the default writer and returns the
  569. * array of tokens it contains. Doing this ahead of time avoids the need to
  570. * parse templates on the fly as they are rendered.
  571. */
  572. mustache.parse = function parse (template, tags) {
  573. return defaultWriter.parse(template, tags);
  574. };
  575. /**
  576. * Renders the `template` with the given `view` and `partials` using the
  577. * default writer. If the optional `tags` argument is given here it must be an
  578. * array with two string values: the opening and closing tags used in the
  579. * template (e.g. [ "<%", "%>" ]). The default is to mustache.tags.
  580. */
  581. mustache.render = function render (template, view, partials, tags) {
  582. if (typeof template !== 'string') {
  583. throw new TypeError('Invalid template! Template should be a "string" ' +
  584. 'but "' + typeStr(template) + '" was given as the first ' +
  585. 'argument for mustache#render(template, view, partials)');
  586. }
  587. return defaultWriter.render(template, view, partials, tags);
  588. };
  589. // This is here for backwards compatibility with 0.4.x.,
  590. /*eslint-disable */ // eslint wants camel cased function name
  591. mustache.to_html = function to_html (template, view, partials, send) {
  592. /*eslint-enable*/
  593. var result = mustache.render(template, view, partials);
  594. if (isFunction(send)) {
  595. send(result);
  596. } else {
  597. return result;
  598. }
  599. };
  600. // Export the escaping function so that the user may override it.
  601. // See https://github.com/janl/mustache.js/issues/244
  602. mustache.escape = escapeHtml;
  603. // Export these mainly for testing, but also for advanced usage.
  604. mustache.Scanner = Scanner;
  605. mustache.Context = Context;
  606. mustache.Writer = Writer;
  607. return mustache;
  608. }));