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.

712 lines
22KB

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