You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

568 lines
16KB

  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 (object) {
  36. return Object_toString.call(object) === '[object Array]';
  37. };
  38. function isFunction(object) {
  39. return typeof object === 'function';
  40. }
  41. function escapeRegExp(string) {
  42. return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
  43. }
  44. var entityMap = {
  45. "&": "&amp;",
  46. "<": "&lt;",
  47. ">": "&gt;",
  48. '"': '&quot;',
  49. "'": '&#39;',
  50. "/": '&#x2F;'
  51. };
  52. function escapeHtml(string) {
  53. return String(string).replace(/[&<>"'\/]/g, function (s) {
  54. return entityMap[s];
  55. });
  56. }
  57. function escapeTags(tags) {
  58. if (!isArray(tags) || tags.length !== 2) {
  59. throw new Error('Invalid tags: ' + tags);
  60. }
  61. return [
  62. new RegExp(escapeRegExp(tags[0]) + "\\s*"),
  63. new RegExp("\\s*" + escapeRegExp(tags[1]))
  64. ];
  65. }
  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 template 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. * in the original template of the token, respectively.
  83. *
  84. * Tokens that are the root node of a subtree contain two more elements: an
  85. * array of tokens in the subtree and the index in the original template at which
  86. * 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(eqRe);
  144. scanner.scan(eqRe);
  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. if (!(template in this.cache)) {
  353. this.cache[template] = parseTemplate(template, tags);
  354. }
  355. return this.cache[template];
  356. };
  357. /**
  358. * High-level method that is used to render the given `template` with
  359. * the given `view`.
  360. *
  361. * The optional `partials` argument may be an object that contains the
  362. * names and templates of partials that are used in the template. It may
  363. * also be a function that is used to load partial templates on the fly
  364. * that takes a single argument: the name of the partial.
  365. */
  366. Writer.prototype.render = function (template, view, partials) {
  367. var tokens = this.parse(template);
  368. var context = (view instanceof Context) ? view : new Context(view);
  369. return this.renderTokens(tokens, context, partials, template);
  370. };
  371. /**
  372. * Low-level method that renders the given array of `tokens` using
  373. * the given `context` and `partials`.
  374. *
  375. * Note: The `originalTemplate` is only ever used to extract the portion
  376. * of the original template that was contained in a higher-order section.
  377. * If the template doesn't use higher-order sections, this argument may
  378. * be omitted.
  379. */
  380. Writer.prototype.renderTokens = function (tokens, context, partials, originalTemplate) {
  381. var buffer = '';
  382. // This function is used to render an arbitrary template
  383. // in the current context by higher-order sections.
  384. var self = this;
  385. function subRender(template) {
  386. return self.render(template, context, partials);
  387. }
  388. var token, value;
  389. for (var i = 0, len = tokens.length; i < len; ++i) {
  390. token = tokens[i];
  391. switch (token[0]) {
  392. case '#':
  393. value = context.lookup(token[1]);
  394. if (!value) continue;
  395. if (isArray(value)) {
  396. for (var j = 0, jlen = value.length; j < jlen; ++j) {
  397. buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
  398. }
  399. } else if (typeof value === 'object' || typeof value === 'string') {
  400. buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
  401. } else if (isFunction(value)) {
  402. if (typeof originalTemplate !== 'string') {
  403. throw new Error('Cannot use higher-order sections without the original template');
  404. }
  405. // Extract the portion of the original template that the section contains.
  406. value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
  407. if (value != null) buffer += value;
  408. } else {
  409. buffer += this.renderTokens(token[4], context, partials, originalTemplate);
  410. }
  411. break;
  412. case '^':
  413. value = context.lookup(token[1]);
  414. // Use JavaScript's definition of falsy. Include empty arrays.
  415. // See https://github.com/janl/mustache.js/issues/186
  416. if (!value || (isArray(value) && value.length === 0)) {
  417. buffer += this.renderTokens(token[4], context, partials, originalTemplate);
  418. }
  419. break;
  420. case '>':
  421. if (!partials) continue;
  422. value = this.parse(isFunction(partials) ? partials(token[1]) : partials[token[1]]);
  423. if (value != null) buffer += this.renderTokens(value, context, partials, originalTemplate);
  424. break;
  425. case '&':
  426. value = context.lookup(token[1]);
  427. if (value != null) buffer += value;
  428. break;
  429. case 'name':
  430. value = context.lookup(token[1]);
  431. if (value != null) buffer += mustache.escape(value);
  432. break;
  433. case 'text':
  434. buffer += token[1];
  435. break;
  436. }
  437. }
  438. return buffer;
  439. };
  440. mustache.name = "mustache.js";
  441. mustache.version = "0.8.0";
  442. mustache.tags = [ "{{", "}}" ];
  443. // All high-level mustache.* functions use this writer.
  444. var defaultWriter = new Writer();
  445. /**
  446. * Clears all cached templates in the default writer.
  447. */
  448. mustache.clearCache = function () {
  449. return defaultWriter.clearCache();
  450. };
  451. /**
  452. * Parses and caches the given template in the default writer and returns the
  453. * array of tokens it contains. Doing this ahead of time avoids the need to
  454. * parse templates on the fly as they are rendered.
  455. */
  456. mustache.parse = function (template, tags) {
  457. return defaultWriter.parse(template, tags);
  458. };
  459. /**
  460. * Renders the `template` with the given `view` and `partials` using the
  461. * default writer.
  462. */
  463. mustache.render = function (template, view, partials) {
  464. return defaultWriter.render(template, view, partials);
  465. };
  466. // This is here for backwards compatibility with 0.4.x.
  467. mustache.to_html = function (template, view, partials, send) {
  468. var result = mustache.render(template, view, partials);
  469. if (isFunction(send)) {
  470. send(result);
  471. } else {
  472. return result;
  473. }
  474. };
  475. // Export the escaping function so that the user may override it.
  476. // See https://github.com/janl/mustache.js/issues/244
  477. mustache.escape = escapeHtml;
  478. // Export these mainly for testing, but also for advanced usage.
  479. mustache.Scanner = Scanner;
  480. mustache.Context = Context;
  481. mustache.Writer = Writer;
  482. }));