25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

718 satır
21KB

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