mustache.mjs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  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.templateCache = {
  412. _cache: {},
  413. set: function set (key, value) {
  414. this._cache[key] = value;
  415. },
  416. get: function get (key) {
  417. return this._cache[key];
  418. },
  419. clear: function clear () {
  420. this._cache = {};
  421. }
  422. };
  423. }
  424. /**
  425. * Clears all cached templates in this writer.
  426. */
  427. Writer.prototype.clearCache = function clearCache () {
  428. if (typeof this.templateCache !== 'undefined') {
  429. this.templateCache.clear();
  430. }
  431. };
  432. /**
  433. * Parses and caches the given `template` according to the given `tags` or
  434. * `mustache.tags` if `tags` is omitted, and returns the array of tokens
  435. * that is generated from the parse.
  436. */
  437. Writer.prototype.parse = function parse (template, tags) {
  438. var cache = this.templateCache;
  439. var cacheKey = template + ':' + (tags || mustache.tags).join(':');
  440. var isCacheEnabled = typeof cache !== 'undefined';
  441. var tokens = isCacheEnabled ? cache.get(cacheKey) : undefined;
  442. if (tokens == undefined) {
  443. tokens = parseTemplate(template, tags);
  444. isCacheEnabled && cache.set(cacheKey, tokens);
  445. }
  446. return tokens;
  447. };
  448. /**
  449. * High-level method that is used to render the given `template` with
  450. * the given `view`.
  451. *
  452. * The optional `partials` argument may be an object that contains the
  453. * names and templates of partials that are used in the template. It may
  454. * also be a function that is used to load partial templates on the fly
  455. * that takes a single argument: the name of the partial.
  456. *
  457. * If the optional `config` argument is given here, then it should be an
  458. * object with a `tags` attribute or an `escape` attribute or both.
  459. * If an array is passed, then it will be interpreted the same way as
  460. * a `tags` attribute on a `config` object.
  461. *
  462. * The `tags` attribute of a `config` object must be an array with two
  463. * string values: the opening and closing tags used in the template (e.g.
  464. * [ "<%", "%>" ]). The default is to mustache.tags.
  465. *
  466. * The `escape` attribute of a `config` object must be a function which
  467. * accepts a string as input and outputs a safely escaped string.
  468. * If an `escape` function is not provided, then an HTML-safe string
  469. * escaping function is used as the default.
  470. */
  471. Writer.prototype.render = function render (template, view, partials, config) {
  472. var tags = this.getConfigTags(config);
  473. var tokens = this.parse(template, tags);
  474. var context = (view instanceof Context) ? view : new Context(view, undefined);
  475. return this.renderTokens(tokens, context, partials, template, config);
  476. };
  477. /**
  478. * Low-level method that renders the given array of `tokens` using
  479. * the given `context` and `partials`.
  480. *
  481. * Note: The `originalTemplate` is only ever used to extract the portion
  482. * of the original template that was contained in a higher-order section.
  483. * If the template doesn't use higher-order sections, this argument may
  484. * be omitted.
  485. */
  486. Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate, config) {
  487. var buffer = '';
  488. var token, symbol, value;
  489. for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
  490. value = undefined;
  491. token = tokens[i];
  492. symbol = token[0];
  493. if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate, config);
  494. else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate, config);
  495. else if (symbol === '>') value = this.renderPartial(token, context, partials, config);
  496. else if (symbol === '&') value = this.unescapedValue(token, context);
  497. else if (symbol === 'name') value = this.escapedValue(token, context, config);
  498. else if (symbol === 'text') value = this.rawValue(token);
  499. if (value !== undefined)
  500. buffer += value;
  501. }
  502. return buffer;
  503. };
  504. Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate, config) {
  505. var self = this;
  506. var buffer = '';
  507. var value = context.lookup(token[1]);
  508. // This function is used to render an arbitrary template
  509. // in the current context by higher-order sections.
  510. function subRender (template) {
  511. return self.render(template, context, partials, config);
  512. }
  513. if (!value) return;
  514. if (isArray(value)) {
  515. for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
  516. buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate, config);
  517. }
  518. } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
  519. buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate, config);
  520. } else if (isFunction(value)) {
  521. if (typeof originalTemplate !== 'string')
  522. throw new Error('Cannot use higher-order sections without the original template');
  523. // Extract the portion of the original template that the section contains.
  524. value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
  525. if (value != null)
  526. buffer += value;
  527. } else {
  528. buffer += this.renderTokens(token[4], context, partials, originalTemplate, config);
  529. }
  530. return buffer;
  531. };
  532. Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate, config) {
  533. var value = context.lookup(token[1]);
  534. // Use JavaScript's definition of falsy. Include empty arrays.
  535. // See https://github.com/janl/mustache.js/issues/186
  536. if (!value || (isArray(value) && value.length === 0))
  537. return this.renderTokens(token[4], context, partials, originalTemplate, config);
  538. };
  539. Writer.prototype.indentPartial = function indentPartial (partial, indentation, lineHasNonSpace) {
  540. var filteredIndentation = indentation.replace(/[^ \t]/g, '');
  541. var partialByNl = partial.split('\n');
  542. for (var i = 0; i < partialByNl.length; i++) {
  543. if (partialByNl[i].length && (i > 0 || !lineHasNonSpace)) {
  544. partialByNl[i] = filteredIndentation + partialByNl[i];
  545. }
  546. }
  547. return partialByNl.join('\n');
  548. };
  549. Writer.prototype.renderPartial = function renderPartial (token, context, partials, config) {
  550. if (!partials) return;
  551. var tags = this.getConfigTags(config);
  552. var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
  553. if (value != null) {
  554. var lineHasNonSpace = token[6];
  555. var tagIndex = token[5];
  556. var indentation = token[4];
  557. var indentedValue = value;
  558. if (tagIndex == 0 && indentation) {
  559. indentedValue = this.indentPartial(value, indentation, lineHasNonSpace);
  560. }
  561. var tokens = this.parse(indentedValue, tags);
  562. return this.renderTokens(tokens, context, partials, indentedValue, config);
  563. }
  564. };
  565. Writer.prototype.unescapedValue = function unescapedValue (token, context) {
  566. var value = context.lookup(token[1]);
  567. if (value != null)
  568. return value;
  569. };
  570. Writer.prototype.escapedValue = function escapedValue (token, context, config) {
  571. var escape = this.getConfigEscape(config) || mustache.escape;
  572. var value = context.lookup(token[1]);
  573. if (value != null)
  574. return (typeof value === 'number' && escape === mustache.escape) ? String(value) : escape(value);
  575. };
  576. Writer.prototype.rawValue = function rawValue (token) {
  577. return token[1];
  578. };
  579. Writer.prototype.getConfigTags = function getConfigTags (config) {
  580. if (isArray(config)) {
  581. return config;
  582. }
  583. else if (config && typeof config === 'object') {
  584. return config.tags;
  585. }
  586. else {
  587. return undefined;
  588. }
  589. };
  590. Writer.prototype.getConfigEscape = function getConfigEscape (config) {
  591. if (config && typeof config === 'object' && !isArray(config)) {
  592. return config.escape;
  593. }
  594. else {
  595. return undefined;
  596. }
  597. };
  598. var mustache = {
  599. name: 'mustache.js',
  600. version: '4.2.0',
  601. tags: [ '{{', '}}' ],
  602. clearCache: undefined,
  603. escape: undefined,
  604. parse: undefined,
  605. render: undefined,
  606. Scanner: undefined,
  607. Context: undefined,
  608. Writer: undefined,
  609. /**
  610. * Allows a user to override the default caching strategy, by providing an
  611. * object with set, get and clear methods. This can also be used to disable
  612. * the cache by setting it to the literal `undefined`.
  613. */
  614. set templateCache (cache) {
  615. defaultWriter.templateCache = cache;
  616. },
  617. /**
  618. * Gets the default or overridden caching object from the default writer.
  619. */
  620. get templateCache () {
  621. return defaultWriter.templateCache;
  622. }
  623. };
  624. // All high-level mustache.* functions use this writer.
  625. var defaultWriter = new Writer();
  626. /**
  627. * Clears all cached templates in the default writer.
  628. */
  629. mustache.clearCache = function clearCache () {
  630. return defaultWriter.clearCache();
  631. };
  632. /**
  633. * Parses and caches the given template in the default writer and returns the
  634. * array of tokens it contains. Doing this ahead of time avoids the need to
  635. * parse templates on the fly as they are rendered.
  636. */
  637. mustache.parse = function parse (template, tags) {
  638. return defaultWriter.parse(template, tags);
  639. };
  640. /**
  641. * Renders the `template` with the given `view`, `partials`, and `config`
  642. * using the default writer.
  643. */
  644. mustache.render = function render (template, view, partials, config) {
  645. if (typeof template !== 'string') {
  646. throw new TypeError('Invalid template! Template should be a "string" ' +
  647. 'but "' + typeStr(template) + '" was given as the first ' +
  648. 'argument for mustache#render(template, view, partials)');
  649. }
  650. return defaultWriter.render(template, view, partials, config);
  651. };
  652. // Export the escaping function so that the user may override it.
  653. // See https://github.com/janl/mustache.js/issues/244
  654. mustache.escape = escapeHtml;
  655. // Export these mainly for testing, but also for advanced usage.
  656. mustache.Scanner = Scanner;
  657. mustache.Context = Context;
  658. mustache.Writer = Writer;
  659. export default mustache;