mustache.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. /*!
  2. * mustache.js - Logic-less {{mustache}} templates with JavaScript
  3. * http://github.com/janl/mustache.js
  4. */
  5. /*global define: false*/
  6. (function (global, factory) {
  7. if (typeof exports === "object" && exports) {
  8. factory(exports); // CommonJS
  9. } else if (typeof define === "function" && define.amd) {
  10. define(['exports'], factory); // AMD
  11. } else {
  12. factory(global.Mustache = {}); // <script>
  13. }
  14. }(this, function (mustache) {
  15. var Object_toString = Object.prototype.toString;
  16. var isArray = Array.isArray || function (object) {
  17. return Object_toString.call(object) === '[object Array]';
  18. };
  19. function isFunction(object) {
  20. return typeof object === 'function';
  21. }
  22. function escapeRegExp(string) {
  23. return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
  24. }
  25. // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
  26. // See https://github.com/janl/mustache.js/issues/189
  27. var RegExp_test = RegExp.prototype.test;
  28. function testRegExp(re, string) {
  29. return RegExp_test.call(re, string);
  30. }
  31. var nonSpaceRe = /\S/;
  32. function isWhitespace(string) {
  33. return !testRegExp(nonSpaceRe, string);
  34. }
  35. var entityMap = {
  36. "&": "&amp;",
  37. "<": "&lt;",
  38. ">": "&gt;",
  39. '"': '&quot;',
  40. "'": '&#39;',
  41. "/": '&#x2F;'
  42. };
  43. function escapeHtml(string) {
  44. return String(string).replace(/[&<>"'\/]/g, function (s) {
  45. return entityMap[s];
  46. });
  47. }
  48. var whiteRe = /\s*/;
  49. var spaceRe = /\s+/;
  50. var equalsRe = /\s*=/;
  51. var curlyRe = /\s*\}/;
  52. var tagRe = /#|\^|\/|>|\{|&|=|!/;
  53. /**
  54. * Breaks up the given `template` string into a tree of tokens. If the `tags`
  55. * argument is given here it must be an array with two string values: the
  56. * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
  57. * course, the default is to use mustaches (i.e. mustache.tags).
  58. *
  59. * A token is an array with at least 4 elements. The first element is the
  60. * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
  61. * did not contain a symbol (i.e. {{myValue}}) this element is "name". For
  62. * all text that appears outside a symbol this element is "text".
  63. *
  64. * The second element of a token is its "value". For mustache tags this is
  65. * whatever else was inside the tag besides the opening symbol. For text tokens
  66. * this is the text itself.
  67. *
  68. * The third and fourth elements of the token are the start and end indices,
  69. * respectively, of the token in the original template.
  70. *
  71. * Tokens that are the root node of a subtree contain two more elements: 1) an
  72. * array of tokens in the subtree and 2) the index in the original template at
  73. * which the closing tag for that section begins.
  74. */
  75. function parseTemplate(template, tags) {
  76. if (!template)
  77. return [];
  78. var sections = []; // Stack to hold section tokens
  79. var tokens = []; // Buffer to hold the tokens
  80. var spaces = []; // Indices of whitespace tokens on the current line
  81. var hasTag = false; // Is there a {{tag}} on the current line?
  82. var nonSpace = false; // Is there a non-space char on the current line?
  83. // Strips all whitespace tokens array for the current line
  84. // if there was a {{#tag}} on it and otherwise only space.
  85. function stripSpace() {
  86. if (hasTag && !nonSpace) {
  87. while (spaces.length)
  88. delete tokens[spaces.pop()];
  89. } else {
  90. spaces = [];
  91. }
  92. hasTag = false;
  93. nonSpace = false;
  94. }
  95. var openingTagRe, closingTagRe, closingCurlyRe;
  96. function compileTags(tags) {
  97. if (typeof tags === 'string')
  98. tags = tags.split(spaceRe, 2);
  99. if (!isArray(tags) || tags.length !== 2)
  100. throw new Error('Invalid tags: ' + tags);
  101. openingTagRe = new RegExp(escapeRegExp(tags[0]) + '\\s*');
  102. closingTagRe = new RegExp('\\s*' + escapeRegExp(tags[1]));
  103. closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tags[1]));
  104. }
  105. compileTags(tags || mustache.tags);
  106. var scanner = new Scanner(template);
  107. var start, type, value, chr, token, openSection;
  108. while (!scanner.eos()) {
  109. start = scanner.pos;
  110. // Match any text between tags.
  111. value = scanner.scanUntil(openingTagRe);
  112. if (value) {
  113. for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
  114. chr = value.charAt(i);
  115. if (isWhitespace(chr)) {
  116. spaces.push(tokens.length);
  117. } else {
  118. nonSpace = true;
  119. }
  120. tokens.push([ 'text', chr, start, start + 1 ]);
  121. start += 1;
  122. // Check for whitespace on the current line.
  123. if (chr === '\n')
  124. stripSpace();
  125. }
  126. }
  127. // Match the opening tag.
  128. if (!scanner.scan(openingTagRe))
  129. break;
  130. hasTag = true;
  131. // Get the tag type.
  132. type = scanner.scan(tagRe) || 'name';
  133. scanner.scan(whiteRe);
  134. // Get the tag value.
  135. if (type === '=') {
  136. value = scanner.scanUntil(equalsRe);
  137. scanner.scan(equalsRe);
  138. scanner.scanUntil(closingTagRe);
  139. } else if (type === '{') {
  140. value = scanner.scanUntil(closingCurlyRe);
  141. scanner.scan(curlyRe);
  142. scanner.scanUntil(closingTagRe);
  143. type = '&';
  144. } else {
  145. value = scanner.scanUntil(closingTagRe);
  146. }
  147. // Match the closing tag.
  148. if (!scanner.scan(closingTagRe))
  149. throw new Error('Unclosed tag at ' + scanner.pos);
  150. token = [ type, value, start, scanner.pos ];
  151. tokens.push(token);
  152. if (type === '#' || type === '^') {
  153. sections.push(token);
  154. } else if (type === '/') {
  155. // Check section nesting.
  156. openSection = sections.pop();
  157. if (!openSection)
  158. throw new Error('Unopened section "' + value + '" at ' + start);
  159. if (openSection[1] !== value)
  160. throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
  161. } else if (type === 'name' || type === '{' || type === '&') {
  162. nonSpace = true;
  163. } else if (type === '=') {
  164. // Set the tags for the next time around.
  165. compileTags(value);
  166. }
  167. }
  168. // Make sure there are no open sections when we're done.
  169. openSection = sections.pop();
  170. if (openSection)
  171. throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
  172. return nestTokens(squashTokens(tokens));
  173. }
  174. /**
  175. * Combines the values of consecutive text tokens in the given `tokens` array
  176. * to a single token.
  177. */
  178. function squashTokens(tokens) {
  179. var squashedTokens = [];
  180. var token, lastToken;
  181. for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
  182. token = tokens[i];
  183. if (token) {
  184. if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
  185. lastToken[1] += token[1];
  186. lastToken[3] = token[3];
  187. } else {
  188. squashedTokens.push(token);
  189. lastToken = token;
  190. }
  191. }
  192. }
  193. return squashedTokens;
  194. }
  195. /**
  196. * Forms the given array of `tokens` into a nested tree structure where
  197. * tokens that represent a section have two additional items: 1) an array of
  198. * all tokens that appear in that section and 2) the index in the original
  199. * template that represents the end of that section.
  200. */
  201. function nestTokens(tokens) {
  202. var nestedTokens = [];
  203. var collector = nestedTokens;
  204. var sections = [];
  205. var token, section;
  206. for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
  207. token = tokens[i];
  208. switch (token[0]) {
  209. case '#':
  210. case '^':
  211. collector.push(token);
  212. sections.push(token);
  213. collector = token[4] = [];
  214. break;
  215. case '/':
  216. section = sections.pop();
  217. section[5] = token[2];
  218. collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
  219. break;
  220. default:
  221. collector.push(token);
  222. }
  223. }
  224. return nestedTokens;
  225. }
  226. /**
  227. * A simple string scanner that is used by the template parser to find
  228. * tokens in template strings.
  229. */
  230. function Scanner(string) {
  231. this.string = string;
  232. this.tail = string;
  233. this.pos = 0;
  234. }
  235. /**
  236. * Returns `true` if the tail is empty (end of string).
  237. */
  238. Scanner.prototype.eos = function () {
  239. return this.tail === "";
  240. };
  241. /**
  242. * Tries to match the given regular expression at the current position.
  243. * Returns the matched text if it can match, the empty string otherwise.
  244. */
  245. Scanner.prototype.scan = function (re) {
  246. var match = this.tail.match(re);
  247. if (!match || match.index !== 0)
  248. return '';
  249. var string = match[0];
  250. this.tail = this.tail.substring(string.length);
  251. this.pos += string.length;
  252. return string;
  253. };
  254. /**
  255. * Skips all text until the given regular expression can be matched. Returns
  256. * the skipped string, which is the entire tail if no match can be made.
  257. */
  258. Scanner.prototype.scanUntil = function (re) {
  259. var index = this.tail.search(re), match;
  260. switch (index) {
  261. case -1:
  262. match = this.tail;
  263. this.tail = "";
  264. break;
  265. case 0:
  266. match = "";
  267. break;
  268. default:
  269. match = this.tail.substring(0, index);
  270. this.tail = this.tail.substring(index);
  271. }
  272. this.pos += match.length;
  273. return match;
  274. };
  275. /**
  276. * Represents a rendering context by wrapping a view object and
  277. * maintaining a reference to the parent context.
  278. */
  279. function Context(view, parentContext) {
  280. this.view = view == null ? {} : view;
  281. this.cache = { '.': this.view };
  282. this.parent = parentContext;
  283. }
  284. /**
  285. * Creates a new context using the given view with this context
  286. * as the parent.
  287. */
  288. Context.prototype.push = function (view) {
  289. return new Context(view, this);
  290. };
  291. /**
  292. * Returns the value of the given name in this context, traversing
  293. * up the context hierarchy if the value is absent in this context's view.
  294. */
  295. Context.prototype.lookup = function (name) {
  296. var cache = this.cache;
  297. var value;
  298. if (name in cache) {
  299. value = cache[name];
  300. } else {
  301. var context = this, names, index;
  302. while (context) {
  303. if (name.indexOf('.') > 0) {
  304. value = context.view;
  305. names = name.split('.');
  306. index = 0;
  307. while (value != null && index < names.length)
  308. value = value[names[index++]];
  309. } else if (typeof context.view == 'object') {
  310. value = context.view[name];
  311. }
  312. if (value != null)
  313. break;
  314. context = context.parent;
  315. }
  316. cache[name] = value;
  317. }
  318. if (isFunction(value))
  319. value = value.call(this.view);
  320. return value;
  321. };
  322. /**
  323. * A Writer knows how to take a stream of tokens and render them to a
  324. * string, given a context. It also maintains a cache of templates to
  325. * avoid the need to parse the same template twice.
  326. */
  327. function Writer() {
  328. this.cache = {};
  329. }
  330. /**
  331. * Clears all cached templates in this writer.
  332. */
  333. Writer.prototype.clearCache = function () {
  334. this.cache = {};
  335. };
  336. /**
  337. * Parses and caches the given `template` and returns the array of tokens
  338. * that is generated from the parse.
  339. */
  340. Writer.prototype.parse = function (template, tags) {
  341. var cache = this.cache;
  342. var tokens = cache[template];
  343. if (tokens == null)
  344. tokens = cache[template] = parseTemplate(template, tags);
  345. return tokens;
  346. };
  347. /**
  348. * High-level method that is used to render the given `template` with
  349. * the given `view`.
  350. *
  351. * The optional `partials` argument may be an object that contains the
  352. * names and templates of partials that are used in the template. It may
  353. * also be a function that is used to load partial templates on the fly
  354. * that takes a single argument: the name of the partial.
  355. */
  356. Writer.prototype.render = function (template, view, partials) {
  357. var tokens = this.parse(template);
  358. var context = (view instanceof Context) ? view : new Context(view);
  359. return this.renderTokens(tokens, context, partials, template);
  360. };
  361. /**
  362. * Low-level method that renders the given array of `tokens` using
  363. * the given `context` and `partials`.
  364. *
  365. * Note: The `originalTemplate` is only ever used to extract the portion
  366. * of the original template that was contained in a higher-order section.
  367. * If the template doesn't use higher-order sections, this argument may
  368. * be omitted.
  369. */
  370. Writer.prototype.renderTokens = function (tokens, context, partials, originalTemplate) {
  371. var buffer = '';
  372. // This function is used to render an arbitrary template
  373. // in the current context by higher-order sections.
  374. var self = this;
  375. function subRender(template) {
  376. return self.render(template, context, partials);
  377. }
  378. var token, value;
  379. for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
  380. token = tokens[i];
  381. switch (token[0]) {
  382. case '#':
  383. value = context.lookup(token[1]);
  384. if (!value)
  385. continue;
  386. if (isArray(value)) {
  387. for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
  388. buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
  389. }
  390. } else if (typeof value === 'object' || typeof value === 'string') {
  391. buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
  392. } else if (isFunction(value)) {
  393. if (typeof originalTemplate !== 'string')
  394. throw new Error('Cannot use higher-order sections without the original template');
  395. // Extract the portion of the original template that the section contains.
  396. value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
  397. if (value != null)
  398. buffer += value;
  399. } else {
  400. buffer += this.renderTokens(token[4], context, partials, originalTemplate);
  401. }
  402. break;
  403. case '^':
  404. value = context.lookup(token[1]);
  405. // Use JavaScript's definition of falsy. Include empty arrays.
  406. // See https://github.com/janl/mustache.js/issues/186
  407. if (!value || (isArray(value) && value.length === 0))
  408. buffer += this.renderTokens(token[4], context, partials, originalTemplate);
  409. break;
  410. case '>':
  411. if (!partials)
  412. continue;
  413. value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
  414. if (value != null)
  415. buffer += this.renderTokens(this.parse(value), context, partials, value);
  416. break;
  417. case '&':
  418. value = context.lookup(token[1]);
  419. if (value != null)
  420. buffer += value;
  421. break;
  422. case 'name':
  423. value = context.lookup(token[1]);
  424. if (value != null)
  425. buffer += mustache.escape(value);
  426. break;
  427. case 'text':
  428. buffer += token[1];
  429. break;
  430. }
  431. }
  432. return buffer;
  433. };
  434. mustache.name = "mustache.js";
  435. mustache.version = "1.0.0";
  436. mustache.tags = [ "{{", "}}" ];
  437. // All high-level mustache.* functions use this writer.
  438. var defaultWriter = new Writer();
  439. /**
  440. * Clears all cached templates in the default writer.
  441. */
  442. mustache.clearCache = function () {
  443. return defaultWriter.clearCache();
  444. };
  445. /**
  446. * Parses and caches the given template in the default writer and returns the
  447. * array of tokens it contains. Doing this ahead of time avoids the need to
  448. * parse templates on the fly as they are rendered.
  449. */
  450. mustache.parse = function (template, tags) {
  451. return defaultWriter.parse(template, tags);
  452. };
  453. /**
  454. * Renders the `template` with the given `view` and `partials` using the
  455. * default writer.
  456. */
  457. mustache.render = function (template, view, partials) {
  458. return defaultWriter.render(template, view, partials);
  459. };
  460. // This is here for backwards compatibility with 0.4.x.
  461. mustache.to_html = function (template, view, partials, send) {
  462. var result = mustache.render(template, view, partials);
  463. if (isFunction(send)) {
  464. send(result);
  465. } else {
  466. return result;
  467. }
  468. };
  469. // Export the escaping function so that the user may override it.
  470. // See https://github.com/janl/mustache.js/issues/244
  471. mustache.escape = escapeHtml;
  472. // Export these mainly for testing, but also for advanced usage.
  473. mustache.Scanner = Scanner;
  474. mustache.Context = Context;
  475. mustache.Writer = Writer;
  476. }));