mustache.js 16 KB

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