Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

614 wiersze
18KB

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