mustache.js 25 KB

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