mustache.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. var whiteRe = /\s*/;
  20. var spaceRe = /\s+/;
  21. var nonSpaceRe = /\S/;
  22. var eqRe = /\s*=/;
  23. var curlyRe = /\s*\}/;
  24. var tagRe = /#|\^|\/|>|\{|&|=|!/;
  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. function isWhitespace(string) {
  32. return !testRegExp(nonSpaceRe, string);
  33. }
  34. var Object_toString = Object.prototype.toString;
  35. var isArray = Array.isArray || function (obj) {
  36. return Object_toString.call(obj) === '[object Array]';
  37. };
  38. function escapeRegExp(string) {
  39. return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
  40. }
  41. var entityMap = {
  42. "&": "&amp;",
  43. "<": "&lt;",
  44. ">": "&gt;",
  45. '"': '&quot;',
  46. "'": '&#39;',
  47. "/": '&#x2F;'
  48. };
  49. function escapeHtml(string) {
  50. return String(string).replace(/[&<>"'\/]/g, function (s) {
  51. return entityMap[s];
  52. });
  53. }
  54. function Scanner(string) {
  55. this.string = string;
  56. this.tail = string;
  57. this.pos = 0;
  58. }
  59. /**
  60. * Returns `true` if the tail is empty (end of string).
  61. */
  62. Scanner.prototype.eos = function () {
  63. return this.tail === "";
  64. };
  65. /**
  66. * Tries to match the given regular expression at the current position.
  67. * Returns the matched text if it can match, the empty string otherwise.
  68. */
  69. Scanner.prototype.scan = function (re) {
  70. var match = this.tail.match(re);
  71. if (match && match.index === 0) {
  72. this.tail = this.tail.substring(match[0].length);
  73. this.pos += match[0].length;
  74. return match[0];
  75. }
  76. return "";
  77. };
  78. /**
  79. * Skips all text until the given regular expression can be matched. Returns
  80. * the skipped string, which is the entire tail if no match can be made.
  81. */
  82. Scanner.prototype.scanUntil = function (re) {
  83. var match, pos = this.tail.search(re);
  84. switch (pos) {
  85. case -1:
  86. match = this.tail;
  87. this.pos += this.tail.length;
  88. this.tail = "";
  89. break;
  90. case 0:
  91. match = "";
  92. break;
  93. default:
  94. match = this.tail.substring(0, pos);
  95. this.tail = this.tail.substring(pos);
  96. this.pos += pos;
  97. }
  98. return match;
  99. };
  100. function Context(view, parent) {
  101. this.view = view || {};
  102. this.parent = parent;
  103. this._cache = {};
  104. }
  105. Context.make = function (view) {
  106. return (view instanceof Context) ? view : new Context(view);
  107. };
  108. Context.prototype.push = function (view) {
  109. return new Context(view, this);
  110. };
  111. Context.prototype.lookup = function (name) {
  112. var value = this._cache[name];
  113. if (!value) {
  114. if (name == '.') {
  115. value = this.view;
  116. } else {
  117. var context = this;
  118. while (context) {
  119. if (name.indexOf('.') > 0) {
  120. value = context.view;
  121. var names = name.split('.'), i = 0;
  122. while (value && i < names.length) {
  123. value = value[names[i++]];
  124. }
  125. } else {
  126. value = context.view[name];
  127. }
  128. if (value != null) break;
  129. context = context.parent;
  130. }
  131. }
  132. this._cache[name] = value;
  133. }
  134. if (typeof value === 'function') value = value.call(this.view);
  135. return value;
  136. };
  137. function Writer() {
  138. this.clearCache();
  139. }
  140. Writer.prototype.clearCache = function () {
  141. this._cache = {};
  142. this._partialCache = {};
  143. };
  144. Writer.prototype.compile = function (template, tags) {
  145. var fn = this._cache[template];
  146. if (!fn) {
  147. var tokens = mustache.parse(template, tags);
  148. fn = this._cache[template] = this.compileTokens(tokens, template);
  149. }
  150. return fn;
  151. };
  152. Writer.prototype.compilePartial = function (name, template, tags) {
  153. var fn = this.compile(template, tags);
  154. this._partialCache[name] = fn;
  155. return fn;
  156. };
  157. Writer.prototype.getPartial = function (name) {
  158. if (!(name in this._partialCache) && this._loadPartial) {
  159. this.compilePartial(name, this._loadPartial(name));
  160. }
  161. return this._partialCache[name];
  162. };
  163. Writer.prototype.compileTokens = function (tokens, template) {
  164. var self = this;
  165. return function (view, partials) {
  166. if (partials) {
  167. if (typeof partials === 'function') {
  168. self._loadPartial = partials;
  169. } else {
  170. for (var name in partials) {
  171. self.compilePartial(name, partials[name]);
  172. }
  173. }
  174. }
  175. return renderTokens(tokens, self, Context.make(view), template);
  176. };
  177. };
  178. Writer.prototype.render = function (template, view, partials) {
  179. return this.compile(template)(view, partials);
  180. };
  181. /**
  182. * Low-level function that renders the given `tokens` using the given `writer`
  183. * and `context`. The `template` string is only needed for templates that use
  184. * higher-order sections to extract the portion of the original template that
  185. * was contained in that section.
  186. */
  187. function renderTokens(tokens, writer, context, template) {
  188. var buffer = '';
  189. var token, tokenValue, value;
  190. for (var i = 0, len = tokens.length; i < len; ++i) {
  191. token = tokens[i];
  192. tokenValue = token[1];
  193. switch (token[0]) {
  194. case '#':
  195. value = context.lookup(tokenValue);
  196. if (typeof value === 'object') {
  197. if (isArray(value)) {
  198. for (var j = 0, jlen = value.length; j < jlen; ++j) {
  199. buffer += renderTokens(token[4], writer, context.push(value[j]), template);
  200. }
  201. } else if (value) {
  202. buffer += renderTokens(token[4], writer, context.push(value), template);
  203. }
  204. } else if (typeof value === 'function') {
  205. var text = template == null ? null : template.slice(token[3], token[5]);
  206. value = value.call(context.view, text, function (template) {
  207. return writer.render(template, context);
  208. });
  209. if (value != null) buffer += value;
  210. } else if (value) {
  211. buffer += renderTokens(token[4], writer, context, template);
  212. }
  213. break;
  214. case '^':
  215. value = context.lookup(tokenValue);
  216. // Use JavaScript's definition of falsy. Include empty arrays.
  217. // See https://github.com/janl/mustache.js/issues/186
  218. if (!value || (isArray(value) && value.length === 0)) {
  219. buffer += renderTokens(token[4], writer, context, template);
  220. }
  221. break;
  222. case '>':
  223. value = writer.getPartial(tokenValue);
  224. if (typeof value === 'function') buffer += value(context);
  225. break;
  226. case '&':
  227. value = context.lookup(tokenValue);
  228. if (value != null) buffer += value;
  229. break;
  230. case 'name':
  231. value = context.lookup(tokenValue);
  232. if (value != null) buffer += mustache.escape(value);
  233. break;
  234. case 'text':
  235. buffer += tokenValue;
  236. break;
  237. }
  238. }
  239. return buffer;
  240. }
  241. /**
  242. * Forms the given array of `tokens` into a nested tree structure where
  243. * tokens that represent a section have two additional items: 1) an array of
  244. * all tokens that appear in that section and 2) the index in the original
  245. * template that represents the end of that section.
  246. */
  247. function nestTokens(tokens) {
  248. var tree = [];
  249. var collector = tree;
  250. var sections = [];
  251. var token;
  252. for (var i = 0, len = tokens.length; i < len; ++i) {
  253. token = tokens[i];
  254. switch (token[0]) {
  255. case '#':
  256. case '^':
  257. sections.push(token);
  258. collector.push(token);
  259. collector = token[4] = [];
  260. break;
  261. case '/':
  262. var section = sections.pop();
  263. section[5] = token[2];
  264. collector = sections.length > 0 ? sections[sections.length - 1][4] : tree;
  265. break;
  266. default:
  267. collector.push(token);
  268. }
  269. }
  270. return tree;
  271. }
  272. /**
  273. * Combines the values of consecutive text tokens in the given `tokens` array
  274. * to a single token.
  275. */
  276. function squashTokens(tokens) {
  277. var squashedTokens = [];
  278. var token, lastToken;
  279. for (var i = 0, len = tokens.length; i < len; ++i) {
  280. token = tokens[i];
  281. if (token) {
  282. if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
  283. lastToken[1] += token[1];
  284. lastToken[3] = token[3];
  285. } else {
  286. lastToken = token;
  287. squashedTokens.push(token);
  288. }
  289. }
  290. }
  291. return squashedTokens;
  292. }
  293. function escapeTags(tags) {
  294. return [
  295. new RegExp(escapeRegExp(tags[0]) + "\\s*"),
  296. new RegExp("\\s*" + escapeRegExp(tags[1]))
  297. ];
  298. }
  299. /**
  300. * Breaks up the given `template` string into a tree of token objects. If
  301. * `tags` is given here it must be an array with two string values: the
  302. * opening and closing tags used in the template (e.g. ["<%", "%>"]). Of
  303. * course, the default is to use mustaches (i.e. Mustache.tags).
  304. */
  305. function parseTemplate(template, tags) {
  306. template = template || '';
  307. tags = tags || mustache.tags;
  308. if (typeof tags === 'string') tags = tags.split(spaceRe);
  309. if (tags.length !== 2) throw new Error('Invalid tags: ' + tags.join(', '));
  310. var tagRes = escapeTags(tags);
  311. var scanner = new Scanner(template);
  312. var sections = []; // Stack to hold section tokens
  313. var tokens = []; // Buffer to hold the tokens
  314. var spaces = []; // Indices of whitespace tokens on the current line
  315. var hasTag = false; // Is there a {{tag}} on the current line?
  316. var nonSpace = false; // Is there a non-space char on the current line?
  317. // Strips all whitespace tokens array for the current line
  318. // if there was a {{#tag}} on it and otherwise only space.
  319. function stripSpace() {
  320. if (hasTag && !nonSpace) {
  321. while (spaces.length) {
  322. delete tokens[spaces.pop()];
  323. }
  324. } else {
  325. spaces = [];
  326. }
  327. hasTag = false;
  328. nonSpace = false;
  329. }
  330. var start, type, value, chr, token;
  331. while (!scanner.eos()) {
  332. start = scanner.pos;
  333. // Match any text between tags.
  334. value = scanner.scanUntil(tagRes[0]);
  335. if (value) {
  336. for (var i = 0, len = value.length; i < len; ++i) {
  337. chr = value.charAt(i);
  338. if (isWhitespace(chr)) {
  339. spaces.push(tokens.length);
  340. } else {
  341. nonSpace = true;
  342. }
  343. tokens.push(['text', chr, start, start + 1]);
  344. start += 1;
  345. // Check for whitespace on the current line.
  346. if (chr == '\n') stripSpace();
  347. }
  348. }
  349. // Match the opening tag.
  350. if (!scanner.scan(tagRes[0])) break;
  351. hasTag = true;
  352. // Get the tag type.
  353. type = scanner.scan(tagRe) || 'name';
  354. scanner.scan(whiteRe);
  355. // Get the tag value.
  356. if (type === '=') {
  357. value = scanner.scanUntil(eqRe);
  358. scanner.scan(eqRe);
  359. scanner.scanUntil(tagRes[1]);
  360. } else if (type === '{') {
  361. value = scanner.scanUntil(new RegExp('\\s*' + escapeRegExp('}' + tags[1])));
  362. scanner.scan(curlyRe);
  363. scanner.scanUntil(tagRes[1]);
  364. type = '&';
  365. } else {
  366. value = scanner.scanUntil(tagRes[1]);
  367. }
  368. // Match the closing tag.
  369. if (!scanner.scan(tagRes[1])) throw new Error('Unclosed tag at ' + scanner.pos);
  370. token = [type, value, start, scanner.pos];
  371. tokens.push(token);
  372. if (type === '#' || type === '^') {
  373. sections.push(token);
  374. } else if (type === '/') {
  375. // Check section nesting.
  376. if (sections.length === 0) throw new Error('Unopened section "' + value + '" at ' + start);
  377. var openSection = sections.pop();
  378. if (openSection[1] !== value) throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
  379. } else if (type === 'name' || type === '{' || type === '&') {
  380. nonSpace = true;
  381. } else if (type === '=') {
  382. // Set the tags for the next time around.
  383. tags = value.split(spaceRe);
  384. if (tags.length !== 2) throw new Error('Invalid tags at ' + start + ': ' + tags.join(', '));
  385. tagRes = escapeTags(tags);
  386. }
  387. }
  388. // Make sure there are no open sections when we're done.
  389. var openSection = sections.pop();
  390. if (openSection) throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
  391. tokens = squashTokens(tokens);
  392. return nestTokens(tokens);
  393. }
  394. mustache.name = "mustache.js";
  395. mustache.version = "0.7.2";
  396. mustache.tags = ["{{", "}}"];
  397. mustache.Scanner = Scanner;
  398. mustache.Context = Context;
  399. mustache.Writer = Writer;
  400. mustache.parse = parseTemplate;
  401. // Export the escaping function so that the user may override it.
  402. // See https://github.com/janl/mustache.js/issues/244
  403. mustache.escape = escapeHtml;
  404. // All Mustache.* functions use this writer.
  405. var defaultWriter = new Writer();
  406. /**
  407. * Clears all cached templates and partials in the default writer.
  408. */
  409. mustache.clearCache = function () {
  410. return defaultWriter.clearCache();
  411. };
  412. /**
  413. * Compiles the given `template` to a reusable function using the default
  414. * writer.
  415. */
  416. mustache.compile = function (template, tags) {
  417. return defaultWriter.compile(template, tags);
  418. };
  419. /**
  420. * Compiles the partial with the given `name` and `template` to a reusable
  421. * function using the default writer.
  422. */
  423. mustache.compilePartial = function (name, template, tags) {
  424. return defaultWriter.compilePartial(name, template, tags);
  425. };
  426. /**
  427. * Compiles the given array of tokens (the output of a parse) to a reusable
  428. * function using the default writer.
  429. */
  430. mustache.compileTokens = function (tokens, template) {
  431. return defaultWriter.compileTokens(tokens, template);
  432. };
  433. /**
  434. * Renders the `template` with the given `view` and `partials` using the
  435. * default writer.
  436. */
  437. mustache.render = function (template, view, partials) {
  438. return defaultWriter.render(template, view, partials);
  439. };
  440. // This is here for backwards compatibility with 0.4.x.
  441. mustache.to_html = function (template, view, partials, send) {
  442. var result = mustache.render(template, view, partials);
  443. if (typeof send === "function") {
  444. send(result);
  445. } else {
  446. return result;
  447. }
  448. };
  449. }));