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.

628 líneas
19KB

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