Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

605 строки
18KB

  1. /*!
  2. * mustache.js - Logic-less {{mustache}} templates with JavaScript
  3. * http://github.com/janl/mustache.js
  4. */
  5. /*global define: false*/
  6. (function defineMustache (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 mustacheFactory (mustache) {
  15. var objectToString = Object.prototype.toString;
  16. var isArray = Array.isArray || function isArrayPolyfill (object) {
  17. return objectToString.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 regExpTest = RegExp.prototype.test;
  28. function testRegExp (re, string) {
  29. return regExpTest.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 fromEntityMap (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 (tagsToCompile) {
  97. if (typeof tagsToCompile === 'string')
  98. tagsToCompile = tagsToCompile.split(spaceRe, 2);
  99. if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)
  100. throw new Error('Invalid tags: ' + tagsToCompile);
  101. openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*');
  102. closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1]));
  103. closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[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 eos () {
  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 scan (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 scanUntil (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;
  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 push (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 lookup (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, lookupHit = false;
  302. while (context) {
  303. if (name.indexOf('.') > 0) {
  304. value = context.view;
  305. names = name.split('.');
  306. index = 0;
  307. /**
  308. * Using the dot notion path in `name`, we descend through the
  309. * nested objects.
  310. *
  311. * To be certain that the lookup has been successful, we have to
  312. * check if the last object in the path actually has the property
  313. * we are looking for. We store the result in `lookupHit`.
  314. *
  315. * This is specially necessary for when the value has been set to
  316. * `undefined` and we want to avoid looking up parent contexts.
  317. **/
  318. while (value != null && index < names.length) {
  319. if (index === names.length - 1 && value != null)
  320. lookupHit = (typeof value === 'object') &&
  321. value.hasOwnProperty(names[index]);
  322. value = value[names[index++]];
  323. }
  324. } else if (context.view != null && typeof context.view === 'object') {
  325. value = context.view[name];
  326. lookupHit = context.view.hasOwnProperty(name);
  327. }
  328. if (lookupHit)
  329. break;
  330. context = context.parent;
  331. }
  332. cache[name] = value;
  333. }
  334. if (isFunction(value))
  335. value = value.call(this.view);
  336. return value;
  337. };
  338. /**
  339. * A Writer knows how to take a stream of tokens and render them to a
  340. * string, given a context. It also maintains a cache of templates to
  341. * avoid the need to parse the same template twice.
  342. */
  343. function Writer () {
  344. this.cache = {};
  345. }
  346. /**
  347. * Clears all cached templates in this writer.
  348. */
  349. Writer.prototype.clearCache = function clearCache () {
  350. this.cache = {};
  351. };
  352. /**
  353. * Parses and caches the given `template` and returns the array of tokens
  354. * that is generated from the parse.
  355. */
  356. Writer.prototype.parse = function parse (template, tags) {
  357. var cache = this.cache;
  358. var tokens = cache[template];
  359. if (tokens == null)
  360. tokens = cache[template] = parseTemplate(template, tags);
  361. return tokens;
  362. };
  363. /**
  364. * High-level method that is used to render the given `template` with
  365. * the given `view`.
  366. *
  367. * The optional `partials` argument may be an object that contains the
  368. * names and templates of partials that are used in the template. It may
  369. * also be a function that is used to load partial templates on the fly
  370. * that takes a single argument: the name of the partial.
  371. */
  372. Writer.prototype.render = function render (template, view, partials) {
  373. var tokens = this.parse(template);
  374. var context = (view instanceof Context) ? view : new Context(view);
  375. return this.renderTokens(tokens, context, partials, template);
  376. };
  377. /**
  378. * Low-level method that renders the given array of `tokens` using
  379. * the given `context` and `partials`.
  380. *
  381. * Note: The `originalTemplate` is only ever used to extract the portion
  382. * of the original template that was contained in a higher-order section.
  383. * If the template doesn't use higher-order sections, this argument may
  384. * be omitted.
  385. */
  386. Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate) {
  387. var buffer = '';
  388. var token, symbol, value;
  389. for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
  390. value = undefined;
  391. token = tokens[i];
  392. symbol = token[0];
  393. if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate);
  394. else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate);
  395. else if (symbol === '>') value = this.renderPartial(token, context, partials, originalTemplate);
  396. else if (symbol === '&') value = this.unescapedValue(token, context);
  397. else if (symbol === 'name') value = this.escapedValue(token, context);
  398. else if (symbol === 'text') value = this.rawValue(token);
  399. if (value !== undefined)
  400. buffer += value;
  401. }
  402. return buffer;
  403. };
  404. Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate) {
  405. var self = this;
  406. var buffer = '';
  407. var value = context.lookup(token[1]);
  408. // This function is used to render an arbitrary template
  409. // in the current context by higher-order sections.
  410. function subRender (template) {
  411. return self.render(template, context, partials);
  412. }
  413. if (!value) return;
  414. if (isArray(value)) {
  415. for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
  416. buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
  417. }
  418. } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
  419. buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
  420. } else if (isFunction(value)) {
  421. if (typeof originalTemplate !== 'string')
  422. throw new Error('Cannot use higher-order sections without the original template');
  423. // Extract the portion of the original template that the section contains.
  424. value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
  425. if (value != null)
  426. buffer += value;
  427. } else {
  428. buffer += this.renderTokens(token[4], context, partials, originalTemplate);
  429. }
  430. return buffer;
  431. };
  432. Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate) {
  433. var value = context.lookup(token[1]);
  434. // Use JavaScript's definition of falsy. Include empty arrays.
  435. // See https://github.com/janl/mustache.js/issues/186
  436. if (!value || (isArray(value) && value.length === 0))
  437. return this.renderTokens(token[4], context, partials, originalTemplate);
  438. };
  439. Writer.prototype.renderPartial = function renderPartial (token, context, partials) {
  440. if (!partials) return;
  441. var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
  442. if (value != null)
  443. return this.renderTokens(this.parse(value), context, partials, value);
  444. };
  445. Writer.prototype.unescapedValue = function unescapedValue (token, context) {
  446. var value = context.lookup(token[1]);
  447. if (value != null)
  448. return value;
  449. };
  450. Writer.prototype.escapedValue = function escapedValue (token, context) {
  451. var value = context.lookup(token[1]);
  452. if (value != null)
  453. return mustache.escape(value);
  454. };
  455. Writer.prototype.rawValue = function rawValue (token) {
  456. return token[1];
  457. };
  458. mustache.name = 'mustache.js';
  459. mustache.version = '2.0.0';
  460. mustache.tags = [ '{{', '}}' ];
  461. // All high-level mustache.* functions use this writer.
  462. var defaultWriter = new Writer();
  463. /**
  464. * Clears all cached templates in the default writer.
  465. */
  466. mustache.clearCache = function clearCache () {
  467. return defaultWriter.clearCache();
  468. };
  469. /**
  470. * Parses and caches the given template in the default writer and returns the
  471. * array of tokens it contains. Doing this ahead of time avoids the need to
  472. * parse templates on the fly as they are rendered.
  473. */
  474. mustache.parse = function parse (template, tags) {
  475. return defaultWriter.parse(template, tags);
  476. };
  477. /**
  478. * Renders the `template` with the given `view` and `partials` using the
  479. * default writer.
  480. */
  481. mustache.render = function render (template, view, partials) {
  482. return defaultWriter.render(template, view, partials);
  483. };
  484. // This is here for backwards compatibility with 0.4.x.,
  485. /*eslint-disable */ // eslint wants camel cased function name
  486. mustache.to_html = function to_html (template, view, partials, send) {
  487. /*eslint-enable*/
  488. var result = mustache.render(template, view, partials);
  489. if (isFunction(send)) {
  490. send(result);
  491. } else {
  492. return result;
  493. }
  494. };
  495. // Export the escaping function so that the user may override it.
  496. // See https://github.com/janl/mustache.js/issues/244
  497. mustache.escape = escapeHtml;
  498. // Export these mainly for testing, but also for advanced usage.
  499. mustache.Scanner = Scanner;
  500. mustache.Context = Context;
  501. mustache.Writer = Writer;
  502. }));