No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

586 líneas
17KB

  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. var token, symbol, value;
  373. for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
  374. value = undefined;
  375. token = tokens[i];
  376. symbol = token[0];
  377. if (symbol === '#') value = this._renderSection(token, context, partials, originalTemplate);
  378. else if (symbol === '^') value = this._renderInverted(token, context, partials, originalTemplate);
  379. else if (symbol === '>') value = this._renderPartial(token, context, partials, originalTemplate);
  380. else if (symbol === '&') value = this._unescapedValue(token, context);
  381. else if (symbol === 'name') value = this._escapedValue(token, context);
  382. else if (symbol === 'text') value = this._rawValue(token);
  383. if (value !== undefined)
  384. buffer += value;
  385. }
  386. return buffer;
  387. };
  388. Writer.prototype._renderSection = function (token, context, partials, originalTemplate) {
  389. var self = this;
  390. var buffer = '';
  391. var value = context.lookup(token[1]);
  392. // This function is used to render an arbitrary template
  393. // in the current context by higher-order sections.
  394. function subRender(template) {
  395. return self.render(template, context, partials);
  396. }
  397. if (!value) return;
  398. if (isArray(value)) {
  399. for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
  400. buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
  401. }
  402. } else if (typeof value === 'object' || typeof value === 'string') {
  403. buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
  404. } else if (isFunction(value)) {
  405. if (typeof originalTemplate !== 'string')
  406. throw new Error('Cannot use higher-order sections without the original template');
  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)
  410. buffer += value;
  411. } else {
  412. buffer += this.renderTokens(token[4], context, partials, originalTemplate);
  413. }
  414. return buffer;
  415. };
  416. Writer.prototype._renderInverted = function(token, context, partials, originalTemplate) {
  417. var value = context.lookup(token[1]);
  418. // Use JavaScript's definition of falsy. Include empty arrays.
  419. // See https://github.com/janl/mustache.js/issues/186
  420. if (!value || (isArray(value) && value.length === 0))
  421. return this.renderTokens(token[4], context, partials, originalTemplate);
  422. };
  423. Writer.prototype._renderPartial = function(token, context, partials, originalTemplate) {
  424. if (!partials) return;
  425. var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
  426. if (value != null)
  427. return this.renderTokens(this.parse(value), context, partials, value);
  428. };
  429. Writer.prototype._unescapedValue = function(token, context) {
  430. var value = context.lookup(token[1]);
  431. if (value != null)
  432. return value;
  433. };
  434. Writer.prototype._escapedValue = function(token, context) {
  435. var value = context.lookup(token[1]);
  436. if (value != null)
  437. return mustache.escape(value);
  438. };
  439. Writer.prototype._rawValue = function(token) {
  440. return token[1];
  441. };
  442. mustache.name = "mustache.js";
  443. mustache.version = "1.0.0";
  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. }));