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.

796 wiersze
24KB

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