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.

mustache.mjs 22KB

Parser rewrite This commit is a complete rewrite of the core mustache.js file with two main goals: 1) a major performance boost and 2) better compliance with the mustache spec. In order to improve performance templates are pre-compiled to JavaScript functions. These compiled functions take a view, a partials object, and an optional callback as arguments. They are cached to prevent unnecessary re-compilation of an already compiled template. Both of these enhancements facilitate a generous boost in performance. A few other notes: - The mustache.js file is now both browser and CommonJS ready without any modification. - The API exposes two main methods: Mustache.compile and Mustache.render. The former is used to generate a function for a given template, while the latter is a higher-level function that is used to compile and render a template in one shot. Mustache.to_html is still available for backwards compatibility. - The concept of pragmas is removed to conform more closely to the original mustache spec. The dot symbol still works to reference the current item in an array. - The parser is much more strict about whitespace than it was before. The rule is simple: if a line contains only a non-variable tag (i.e. not {{tag}} or {{{tag}}}) and whitespace, that line is ignored in the output. Users may use the "space" option when compiling templates to preserve every whitespace character in the original template. - The parser is able to provide detailed information about where errors occur when parsing and rendering templates, including the line number and surrounding code context.
14 yıl önce
12 yıl önce
12 yıl önce
12 yıl önce
Parser rewrite This commit is a complete rewrite of the core mustache.js file with two main goals: 1) a major performance boost and 2) better compliance with the mustache spec. In order to improve performance templates are pre-compiled to JavaScript functions. These compiled functions take a view, a partials object, and an optional callback as arguments. They are cached to prevent unnecessary re-compilation of an already compiled template. Both of these enhancements facilitate a generous boost in performance. A few other notes: - The mustache.js file is now both browser and CommonJS ready without any modification. - The API exposes two main methods: Mustache.compile and Mustache.render. The former is used to generate a function for a given template, while the latter is a higher-level function that is used to compile and render a template in one shot. Mustache.to_html is still available for backwards compatibility. - The concept of pragmas is removed to conform more closely to the original mustache spec. The dot symbol still works to reference the current item in an array. - The parser is much more strict about whitespace than it was before. The rule is simple: if a line contains only a non-variable tag (i.e. not {{tag}} or {{{tag}}}) and whitespace, that line is ignored in the output. Users may use the "space" option when compiling templates to preserve every whitespace character in the original template. - The parser is able to provide detailed information about where errors occur when parsing and rendering templates, including the line number and surrounding code context.
14 yıl önce
Parser rewrite This commit is a complete rewrite of the core mustache.js file with two main goals: 1) a major performance boost and 2) better compliance with the mustache spec. In order to improve performance templates are pre-compiled to JavaScript functions. These compiled functions take a view, a partials object, and an optional callback as arguments. They are cached to prevent unnecessary re-compilation of an already compiled template. Both of these enhancements facilitate a generous boost in performance. A few other notes: - The mustache.js file is now both browser and CommonJS ready without any modification. - The API exposes two main methods: Mustache.compile and Mustache.render. The former is used to generate a function for a given template, while the latter is a higher-level function that is used to compile and render a template in one shot. Mustache.to_html is still available for backwards compatibility. - The concept of pragmas is removed to conform more closely to the original mustache spec. The dot symbol still works to reference the current item in an array. - The parser is much more strict about whitespace than it was before. The rule is simple: if a line contains only a non-variable tag (i.e. not {{tag}} or {{{tag}}}) and whitespace, that line is ignored in the output. Users may use the "space" option when compiling templates to preserve every whitespace character in the original template. - The parser is able to provide detailed information about where errors occur when parsing and rendering templates, including the line number and surrounding code context.
14 yıl önce
Parser rewrite This commit is a complete rewrite of the core mustache.js file with two main goals: 1) a major performance boost and 2) better compliance with the mustache spec. In order to improve performance templates are pre-compiled to JavaScript functions. These compiled functions take a view, a partials object, and an optional callback as arguments. They are cached to prevent unnecessary re-compilation of an already compiled template. Both of these enhancements facilitate a generous boost in performance. A few other notes: - The mustache.js file is now both browser and CommonJS ready without any modification. - The API exposes two main methods: Mustache.compile and Mustache.render. The former is used to generate a function for a given template, while the latter is a higher-level function that is used to compile and render a template in one shot. Mustache.to_html is still available for backwards compatibility. - The concept of pragmas is removed to conform more closely to the original mustache spec. The dot symbol still works to reference the current item in an array. - The parser is much more strict about whitespace than it was before. The rule is simple: if a line contains only a non-variable tag (i.e. not {{tag}} or {{{tag}}}) and whitespace, that line is ignored in the output. Users may use the "space" option when compiling templates to preserve every whitespace character in the original template. - The parser is able to provide detailed information about where errors occur when parsing and rendering templates, including the line number and surrounding code context.
14 yıl önce
12 yıl önce
Parser rewrite This commit is a complete rewrite of the core mustache.js file with two main goals: 1) a major performance boost and 2) better compliance with the mustache spec. In order to improve performance templates are pre-compiled to JavaScript functions. These compiled functions take a view, a partials object, and an optional callback as arguments. They are cached to prevent unnecessary re-compilation of an already compiled template. Both of these enhancements facilitate a generous boost in performance. A few other notes: - The mustache.js file is now both browser and CommonJS ready without any modification. - The API exposes two main methods: Mustache.compile and Mustache.render. The former is used to generate a function for a given template, while the latter is a higher-level function that is used to compile and render a template in one shot. Mustache.to_html is still available for backwards compatibility. - The concept of pragmas is removed to conform more closely to the original mustache spec. The dot symbol still works to reference the current item in an array. - The parser is much more strict about whitespace than it was before. The rule is simple: if a line contains only a non-variable tag (i.e. not {{tag}} or {{{tag}}}) and whitespace, that line is ignored in the output. Users may use the "space" option when compiling templates to preserve every whitespace character in the original template. - The parser is able to provide detailed information about where errors occur when parsing and rendering templates, including the line number and surrounding code context.
14 yıl önce
12 yıl önce
15 yıl önce
Parser rewrite This commit is a complete rewrite of the core mustache.js file with two main goals: 1) a major performance boost and 2) better compliance with the mustache spec. In order to improve performance templates are pre-compiled to JavaScript functions. These compiled functions take a view, a partials object, and an optional callback as arguments. They are cached to prevent unnecessary re-compilation of an already compiled template. Both of these enhancements facilitate a generous boost in performance. A few other notes: - The mustache.js file is now both browser and CommonJS ready without any modification. - The API exposes two main methods: Mustache.compile and Mustache.render. The former is used to generate a function for a given template, while the latter is a higher-level function that is used to compile and render a template in one shot. Mustache.to_html is still available for backwards compatibility. - The concept of pragmas is removed to conform more closely to the original mustache spec. The dot symbol still works to reference the current item in an array. - The parser is much more strict about whitespace than it was before. The rule is simple: if a line contains only a non-variable tag (i.e. not {{tag}} or {{{tag}}}) and whitespace, that line is ignored in the output. Users may use the "space" option when compiling templates to preserve every whitespace character in the original template. - The parser is able to provide detailed information about where errors occur when parsing and rendering templates, including the line number and surrounding code context.
14 yıl önce
11 yıl önce
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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 `tags` argument is given here it must be an array with two
  458. * string values: the opening and closing tags used in the template (e.g.
  459. * [ "<%", "%>" ]). The default is to mustache.tags.
  460. */
  461. Writer.prototype.render = function render (template, view, partials, tags) {
  462. var tokens = this.parse(template, tags);
  463. var context = (view instanceof Context) ? view : new Context(view, undefined);
  464. return this.renderTokens(tokens, context, partials, template, tags);
  465. };
  466. /**
  467. * Low-level method that renders the given array of `tokens` using
  468. * the given `context` and `partials`.
  469. *
  470. * Note: The `originalTemplate` is only ever used to extract the portion
  471. * of the original template that was contained in a higher-order section.
  472. * If the template doesn't use higher-order sections, this argument may
  473. * be omitted.
  474. */
  475. Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate, tags) {
  476. var buffer = '';
  477. var token, symbol, value;
  478. for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
  479. value = undefined;
  480. token = tokens[i];
  481. symbol = token[0];
  482. if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate);
  483. else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate);
  484. else if (symbol === '>') value = this.renderPartial(token, context, partials, tags);
  485. else if (symbol === '&') value = this.unescapedValue(token, context);
  486. else if (symbol === 'name') value = this.escapedValue(token, context);
  487. else if (symbol === 'text') value = this.rawValue(token);
  488. if (value !== undefined)
  489. buffer += value;
  490. }
  491. return buffer;
  492. };
  493. Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate) {
  494. var self = this;
  495. var buffer = '';
  496. var value = context.lookup(token[1]);
  497. // This function is used to render an arbitrary template
  498. // in the current context by higher-order sections.
  499. function subRender (template) {
  500. return self.render(template, context, partials);
  501. }
  502. if (!value) return;
  503. if (isArray(value)) {
  504. for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
  505. buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
  506. }
  507. } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
  508. buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
  509. } else if (isFunction(value)) {
  510. if (typeof originalTemplate !== 'string')
  511. throw new Error('Cannot use higher-order sections without the original template');
  512. // Extract the portion of the original template that the section contains.
  513. value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
  514. if (value != null)
  515. buffer += value;
  516. } else {
  517. buffer += this.renderTokens(token[4], context, partials, originalTemplate);
  518. }
  519. return buffer;
  520. };
  521. Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate) {
  522. var value = context.lookup(token[1]);
  523. // Use JavaScript's definition of falsy. Include empty arrays.
  524. // See https://github.com/janl/mustache.js/issues/186
  525. if (!value || (isArray(value) && value.length === 0))
  526. return this.renderTokens(token[4], context, partials, originalTemplate);
  527. };
  528. Writer.prototype.indentPartial = function indentPartial (partial, indentation, lineHasNonSpace) {
  529. var filteredIndentation = indentation.replace(/[^ \t]/g, '');
  530. var partialByNl = partial.split('\n');
  531. for (var i = 0; i < partialByNl.length; i++) {
  532. if (partialByNl[i].length && (i > 0 || !lineHasNonSpace)) {
  533. partialByNl[i] = filteredIndentation + partialByNl[i];
  534. }
  535. }
  536. return partialByNl.join('\n');
  537. };
  538. Writer.prototype.renderPartial = function renderPartial (token, context, partials, tags) {
  539. if (!partials) return;
  540. var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
  541. if (value != null) {
  542. var lineHasNonSpace = token[6];
  543. var tagIndex = token[5];
  544. var indentation = token[4];
  545. var indentedValue = value;
  546. if (tagIndex == 0 && indentation) {
  547. indentedValue = this.indentPartial(value, indentation, lineHasNonSpace);
  548. }
  549. return this.renderTokens(this.parse(indentedValue, tags), context, partials, indentedValue);
  550. }
  551. };
  552. Writer.prototype.unescapedValue = function unescapedValue (token, context) {
  553. var value = context.lookup(token[1]);
  554. if (value != null)
  555. return value;
  556. };
  557. Writer.prototype.escapedValue = function escapedValue (token, context) {
  558. var value = context.lookup(token[1]);
  559. if (value != null)
  560. return mustache.escape(value);
  561. };
  562. Writer.prototype.rawValue = function rawValue (token) {
  563. return token[1];
  564. };
  565. var mustache = {
  566. name: 'mustache.js',
  567. version: '4.0.0',
  568. tags: [ '{{', '}}' ],
  569. clearCache: undefined,
  570. escape: undefined,
  571. parse: undefined,
  572. render: undefined,
  573. Scanner: undefined,
  574. Context: undefined,
  575. Writer: undefined,
  576. /**
  577. * Allows a user to override the default caching strategy, by providing an
  578. * object with set, get and clear methods. This can also be used to disable
  579. * the cache by setting it to the literal `undefined`.
  580. */
  581. set templateCache (cache) {
  582. defaultWriter.templateCache = cache;
  583. },
  584. /**
  585. * Gets the default or overridden caching object from the default writer.
  586. */
  587. get templateCache () {
  588. return defaultWriter.templateCache;
  589. }
  590. };
  591. // All high-level mustache.* functions use this writer.
  592. var defaultWriter = new Writer();
  593. /**
  594. * Clears all cached templates in the default writer.
  595. */
  596. mustache.clearCache = function clearCache () {
  597. return defaultWriter.clearCache();
  598. };
  599. /**
  600. * Parses and caches the given template in the default writer and returns the
  601. * array of tokens it contains. Doing this ahead of time avoids the need to
  602. * parse templates on the fly as they are rendered.
  603. */
  604. mustache.parse = function parse (template, tags) {
  605. return defaultWriter.parse(template, tags);
  606. };
  607. /**
  608. * Renders the `template` with the given `view` and `partials` using the
  609. * default writer. If the optional `tags` argument is given here it must be an
  610. * array with two string values: the opening and closing tags used in the
  611. * template (e.g. [ "<%", "%>" ]). The default is to mustache.tags.
  612. */
  613. mustache.render = function render (template, view, partials, tags) {
  614. if (typeof template !== 'string') {
  615. throw new TypeError('Invalid template! Template should be a "string" ' +
  616. 'but "' + typeStr(template) + '" was given as the first ' +
  617. 'argument for mustache#render(template, view, partials)');
  618. }
  619. return defaultWriter.render(template, view, partials, tags);
  620. };
  621. // Export the escaping function so that the user may override it.
  622. // See https://github.com/janl/mustache.js/issues/244
  623. mustache.escape = escapeHtml;
  624. // Export these mainly for testing, but also for advanced usage.
  625. mustache.Scanner = Scanner;
  626. mustache.Context = Context;
  627. mustache.Writer = Writer;
  628. export default mustache;