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.

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