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.

683 lines
21KB

  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. function parseTemplate (template, tags) {
  105. if (!template)
  106. return [];
  107. var sections = []; // Stack to hold section tokens
  108. var tokens = []; // Buffer to hold the tokens
  109. var spaces = []; // Indices of whitespace tokens on the current line
  110. var hasTag = false; // Is there a {{tag}} on the current line?
  111. var nonSpace = false; // Is there a non-space char on the current line?
  112. // Strips all whitespace tokens array for the current line
  113. // if there was a {{#tag}} on it and otherwise only space.
  114. function stripSpace () {
  115. if (hasTag && !nonSpace) {
  116. while (spaces.length)
  117. delete tokens[spaces.pop()];
  118. } else {
  119. spaces = [];
  120. }
  121. hasTag = false;
  122. nonSpace = false;
  123. }
  124. var openingTagRe, closingTagRe, closingCurlyRe;
  125. function compileTags (tagsToCompile) {
  126. if (typeof tagsToCompile === 'string')
  127. tagsToCompile = tagsToCompile.split(spaceRe, 2);
  128. if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)
  129. throw new Error('Invalid tags: ' + tagsToCompile);
  130. openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*');
  131. closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1]));
  132. closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1]));
  133. }
  134. compileTags(tags || mustache.tags);
  135. var scanner = new Scanner(template);
  136. var start, type, value, chr, token, openSection;
  137. while (!scanner.eos()) {
  138. start = scanner.pos;
  139. // Match any text between tags.
  140. value = scanner.scanUntil(openingTagRe);
  141. if (value) {
  142. for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
  143. chr = value.charAt(i);
  144. if (isWhitespace(chr)) {
  145. spaces.push(tokens.length);
  146. } else {
  147. nonSpace = true;
  148. }
  149. tokens.push([ 'text', chr, start, start + 1 ]);
  150. start += 1;
  151. // Check for whitespace on the current line.
  152. if (chr === '\n')
  153. stripSpace();
  154. }
  155. }
  156. // Match the opening tag.
  157. if (!scanner.scan(openingTagRe))
  158. break;
  159. hasTag = true;
  160. // Get the tag type.
  161. type = scanner.scan(tagRe) || 'name';
  162. scanner.scan(whiteRe);
  163. // Get the tag value.
  164. if (type === '=') {
  165. value = scanner.scanUntil(equalsRe);
  166. scanner.scan(equalsRe);
  167. scanner.scanUntil(closingTagRe);
  168. } else if (type === '{') {
  169. value = scanner.scanUntil(closingCurlyRe);
  170. scanner.scan(curlyRe);
  171. scanner.scanUntil(closingTagRe);
  172. type = '&';
  173. } else {
  174. value = scanner.scanUntil(closingTagRe);
  175. }
  176. // Match the closing tag.
  177. if (!scanner.scan(closingTagRe))
  178. throw new Error('Unclosed tag at ' + scanner.pos);
  179. token = [ type, value, start, scanner.pos ];
  180. tokens.push(token);
  181. if (type === '#' || type === '^') {
  182. sections.push(token);
  183. } else if (type === '/') {
  184. // Check section nesting.
  185. openSection = sections.pop();
  186. if (!openSection)
  187. throw new Error('Unopened section "' + value + '" at ' + start);
  188. if (openSection[1] !== value)
  189. throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
  190. } else if (type === 'name' || type === '{' || type === '&') {
  191. nonSpace = true;
  192. } else if (type === '=') {
  193. // Set the tags for the next time around.
  194. compileTags(value);
  195. }
  196. }
  197. // Make sure there are no open sections when we're done.
  198. openSection = sections.pop();
  199. if (openSection)
  200. throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
  201. return nestTokens(squashTokens(tokens));
  202. }
  203. /**
  204. * Combines the values of consecutive text tokens in the given `tokens` array
  205. * to a single token.
  206. */
  207. function squashTokens (tokens) {
  208. var squashedTokens = [];
  209. var token, lastToken;
  210. for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
  211. token = tokens[i];
  212. if (token) {
  213. if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
  214. lastToken[1] += token[1];
  215. lastToken[3] = token[3];
  216. } else {
  217. squashedTokens.push(token);
  218. lastToken = token;
  219. }
  220. }
  221. }
  222. return squashedTokens;
  223. }
  224. /**
  225. * Forms the given array of `tokens` into a nested tree structure where
  226. * tokens that represent a section have two additional items: 1) an array of
  227. * all tokens that appear in that section and 2) the index in the original
  228. * template that represents the end of that section.
  229. */
  230. function nestTokens (tokens) {
  231. var nestedTokens = [];
  232. var collector = nestedTokens;
  233. var sections = [];
  234. var token, section;
  235. for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
  236. token = tokens[i];
  237. switch (token[0]) {
  238. case '#':
  239. case '^':
  240. collector.push(token);
  241. sections.push(token);
  242. collector = token[4] = [];
  243. break;
  244. case '/':
  245. section = sections.pop();
  246. section[5] = token[2];
  247. collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
  248. break;
  249. default:
  250. collector.push(token);
  251. }
  252. }
  253. return nestedTokens;
  254. }
  255. /**
  256. * A simple string scanner that is used by the template parser to find
  257. * tokens in template strings.
  258. */
  259. function Scanner (string) {
  260. this.string = string;
  261. this.tail = string;
  262. this.pos = 0;
  263. }
  264. /**
  265. * Returns `true` if the tail is empty (end of string).
  266. */
  267. Scanner.prototype.eos = function eos () {
  268. return this.tail === '';
  269. };
  270. /**
  271. * Tries to match the given regular expression at the current position.
  272. * Returns the matched text if it can match, the empty string otherwise.
  273. */
  274. Scanner.prototype.scan = function scan (re) {
  275. var match = this.tail.match(re);
  276. if (!match || match.index !== 0)
  277. return '';
  278. var string = match[0];
  279. this.tail = this.tail.substring(string.length);
  280. this.pos += string.length;
  281. return string;
  282. };
  283. /**
  284. * Skips all text until the given regular expression can be matched. Returns
  285. * the skipped string, which is the entire tail if no match can be made.
  286. */
  287. Scanner.prototype.scanUntil = function scanUntil (re) {
  288. var index = this.tail.search(re), match;
  289. switch (index) {
  290. case -1:
  291. match = this.tail;
  292. this.tail = '';
  293. break;
  294. case 0:
  295. match = '';
  296. break;
  297. default:
  298. match = this.tail.substring(0, index);
  299. this.tail = this.tail.substring(index);
  300. }
  301. this.pos += match.length;
  302. return match;
  303. };
  304. /**
  305. * Represents a rendering context by wrapping a view object and
  306. * maintaining a reference to the parent context.
  307. */
  308. function Context (view, parentContext) {
  309. this.view = view;
  310. this.cache = { '.': this.view };
  311. this.parent = parentContext;
  312. }
  313. /**
  314. * Creates a new context using the given view with this context
  315. * as the parent.
  316. */
  317. Context.prototype.push = function push (view) {
  318. return new Context(view, this);
  319. };
  320. /**
  321. * Returns the value of the given name in this context, traversing
  322. * up the context hierarchy if the value is absent in this context's view.
  323. */
  324. Context.prototype.lookup = function lookup (name) {
  325. var cache = this.cache;
  326. var value;
  327. if (cache.hasOwnProperty(name)) {
  328. value = cache[name];
  329. } else {
  330. var context = this, intermediateValue, names, index, lookupHit = false;
  331. while (context) {
  332. if (name.indexOf('.') > 0) {
  333. intermediateValue = context.view;
  334. names = name.split('.');
  335. index = 0;
  336. /**
  337. * Using the dot notion path in `name`, we descend through the
  338. * nested objects.
  339. *
  340. * To be certain that the lookup has been successful, we have to
  341. * check if the last object in the path actually has the property
  342. * we are looking for. We store the result in `lookupHit`.
  343. *
  344. * This is specially necessary for when the value has been set to
  345. * `undefined` and we want to avoid looking up parent contexts.
  346. *
  347. * In the case where dot notation is used, we consider the lookup
  348. * to be successful even if the last "object" in the path is
  349. * not actually an object but a primitive (e.g., a string, or an
  350. * integer), because it is sometimes useful to access a property
  351. * of an autoboxed primitive, such as the length of a string.
  352. **/
  353. while (intermediateValue != null && index < names.length) {
  354. if (index === names.length - 1)
  355. lookupHit = (
  356. hasProperty(intermediateValue, names[index])
  357. || primitiveHasOwnProperty(intermediateValue, names[index])
  358. );
  359. intermediateValue = intermediateValue[names[index++]];
  360. }
  361. } else {
  362. intermediateValue = context.view[name];
  363. /**
  364. * Only checking against `hasProperty`, which always returns `false` if
  365. * `context.view` is not an object. Deliberately omitting the check
  366. * against `primitiveHasOwnProperty` if dot notation is not used.
  367. *
  368. * Consider this example:
  369. * ```
  370. * Mustache.render("The length of a football field is {{#length}}{{length}}{{/length}}.", {length: "100 yards"})
  371. * ```
  372. *
  373. * If we were to check also against `primitiveHasOwnProperty`, as we do
  374. * in the dot notation case, then render call would return:
  375. *
  376. * "The length of a football field is 9."
  377. *
  378. * rather than the expected:
  379. *
  380. * "The length of a football field is 100 yards."
  381. **/
  382. lookupHit = hasProperty(context.view, name);
  383. }
  384. if (lookupHit) {
  385. value = intermediateValue;
  386. break;
  387. }
  388. context = context.parent;
  389. }
  390. cache[name] = value;
  391. }
  392. if (isFunction(value))
  393. value = value.call(this.view);
  394. return value;
  395. };
  396. /**
  397. * A Writer knows how to take a stream of tokens and render them to a
  398. * string, given a context. It also maintains a cache of templates to
  399. * avoid the need to parse the same template twice.
  400. */
  401. function Writer () {
  402. this.cache = {};
  403. }
  404. /**
  405. * Clears all cached templates in this writer.
  406. */
  407. Writer.prototype.clearCache = function clearCache () {
  408. this.cache = {};
  409. };
  410. /**
  411. * Parses and caches the given `template` according to the given `tags` or
  412. * `mustache.tags` if `tags` is omitted, and returns the array of tokens
  413. * that is generated from the parse.
  414. */
  415. Writer.prototype.parse = function parse (template, tags) {
  416. var cache = this.cache;
  417. var cacheKey = template + ':' + (tags || mustache.tags).join(':');
  418. var tokens = cache[cacheKey];
  419. if (tokens == null)
  420. tokens = cache[cacheKey] = parseTemplate(template, tags);
  421. return tokens;
  422. };
  423. /**
  424. * High-level method that is used to render the given `template` with
  425. * the given `view`.
  426. *
  427. * The optional `partials` argument may be an object that contains the
  428. * names and templates of partials that are used in the template. It may
  429. * also be a function that is used to load partial templates on the fly
  430. * that takes a single argument: the name of the partial.
  431. *
  432. * If the optional `tags` argument is given here it must be an array with two
  433. * string values: the opening and closing tags used in the template (e.g.
  434. * [ "<%", "%>" ]). The default is to mustache.tags.
  435. */
  436. Writer.prototype.render = function render (template, view, partials, tags) {
  437. var tokens = this.parse(template, tags);
  438. var context = (view instanceof Context) ? view : new Context(view);
  439. return this.renderTokens(tokens, context, partials, template);
  440. };
  441. /**
  442. * Low-level method that renders the given array of `tokens` using
  443. * the given `context` and `partials`.
  444. *
  445. * Note: The `originalTemplate` is only ever used to extract the portion
  446. * of the original template that was contained in a higher-order section.
  447. * If the template doesn't use higher-order sections, this argument may
  448. * be omitted.
  449. */
  450. Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate) {
  451. var buffer = '';
  452. var token, symbol, value;
  453. for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
  454. value = undefined;
  455. token = tokens[i];
  456. symbol = token[0];
  457. if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate);
  458. else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate);
  459. else if (symbol === '>') value = this.renderPartial(token, context, partials, originalTemplate);
  460. else if (symbol === '&') value = this.unescapedValue(token, context);
  461. else if (symbol === 'name') value = this.escapedValue(token, context);
  462. else if (symbol === 'text') value = this.rawValue(token);
  463. if (value !== undefined)
  464. buffer += value;
  465. }
  466. return buffer;
  467. };
  468. Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate) {
  469. var self = this;
  470. var buffer = '';
  471. var value = context.lookup(token[1]);
  472. // This function is used to render an arbitrary template
  473. // in the current context by higher-order sections.
  474. function subRender (template) {
  475. return self.render(template, context, partials);
  476. }
  477. if (!value) return;
  478. if (isArray(value)) {
  479. for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
  480. buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
  481. }
  482. } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
  483. buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
  484. } else if (isFunction(value)) {
  485. if (typeof originalTemplate !== 'string')
  486. throw new Error('Cannot use higher-order sections without the original template');
  487. // Extract the portion of the original template that the section contains.
  488. value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
  489. if (value != null)
  490. buffer += value;
  491. } else {
  492. buffer += this.renderTokens(token[4], context, partials, originalTemplate);
  493. }
  494. return buffer;
  495. };
  496. Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate) {
  497. var value = context.lookup(token[1]);
  498. // Use JavaScript's definition of falsy. Include empty arrays.
  499. // See https://github.com/janl/mustache.js/issues/186
  500. if (!value || (isArray(value) && value.length === 0))
  501. return this.renderTokens(token[4], context, partials, originalTemplate);
  502. };
  503. Writer.prototype.renderPartial = function renderPartial (token, context, partials) {
  504. if (!partials) return;
  505. var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
  506. if (value != null)
  507. return this.renderTokens(this.parse(value), context, partials, value);
  508. };
  509. Writer.prototype.unescapedValue = function unescapedValue (token, context) {
  510. var value = context.lookup(token[1]);
  511. if (value != null)
  512. return value;
  513. };
  514. Writer.prototype.escapedValue = function escapedValue (token, context) {
  515. var value = context.lookup(token[1]);
  516. if (value != null)
  517. return mustache.escape(value);
  518. };
  519. Writer.prototype.rawValue = function rawValue (token) {
  520. return token[1];
  521. };
  522. mustache.name = 'mustache.js';
  523. mustache.version = '2.3.2';
  524. mustache.tags = [ '{{', '}}' ];
  525. // All high-level mustache.* functions use this writer.
  526. var defaultWriter = new Writer();
  527. /**
  528. * Clears all cached templates in the default writer.
  529. */
  530. mustache.clearCache = function clearCache () {
  531. return defaultWriter.clearCache();
  532. };
  533. /**
  534. * Parses and caches the given template in the default writer and returns the
  535. * array of tokens it contains. Doing this ahead of time avoids the need to
  536. * parse templates on the fly as they are rendered.
  537. */
  538. mustache.parse = function parse (template, tags) {
  539. return defaultWriter.parse(template, tags);
  540. };
  541. /**
  542. * Renders the `template` with the given `view` and `partials` using the
  543. * default writer. If the optional `tags` argument is given here it must be an
  544. * array with two string values: the opening and closing tags used in the
  545. * template (e.g. [ "<%", "%>" ]). The default is to mustache.tags.
  546. */
  547. mustache.render = function render (template, view, partials, tags) {
  548. if (typeof template !== 'string') {
  549. throw new TypeError('Invalid template! Template should be a "string" ' +
  550. 'but "' + typeStr(template) + '" was given as the first ' +
  551. 'argument for mustache#render(template, view, partials)');
  552. }
  553. return defaultWriter.render(template, view, partials, tags);
  554. };
  555. // This is here for backwards compatibility with 0.4.x.,
  556. /*eslint-disable */ // eslint wants camel cased function name
  557. mustache.to_html = function to_html (template, view, partials, send) {
  558. /*eslint-enable*/
  559. var result = mustache.render(template, view, partials);
  560. if (isFunction(send)) {
  561. send(result);
  562. } else {
  563. return result;
  564. }
  565. };
  566. // Export the escaping function so that the user may override it.
  567. // See https://github.com/janl/mustache.js/issues/244
  568. mustache.escape = escapeHtml;
  569. // Export these mainly for testing, but also for advanced usage.
  570. mustache.Scanner = Scanner;
  571. mustache.Context = Context;
  572. mustache.Writer = Writer;
  573. return mustache;
  574. }));