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.

253 lines
9.6 KiB

4 years ago
  1. var assignInWith = require('./assignInWith'),
  2. attempt = require('./attempt'),
  3. baseValues = require('./_baseValues'),
  4. customDefaultsAssignIn = require('./_customDefaultsAssignIn'),
  5. escapeStringChar = require('./_escapeStringChar'),
  6. isError = require('./isError'),
  7. isIterateeCall = require('./_isIterateeCall'),
  8. keys = require('./keys'),
  9. reInterpolate = require('./_reInterpolate'),
  10. templateSettings = require('./templateSettings'),
  11. toString = require('./toString');
  12. /** Used to match empty string literals in compiled template source. */
  13. var reEmptyStringLeading = /\b__p \+= '';/g,
  14. reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
  15. reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
  16. /**
  17. * Used to match
  18. * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
  19. */
  20. var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
  21. /** Used to ensure capturing order of template delimiters. */
  22. var reNoMatch = /($^)/;
  23. /** Used to match unescaped characters in compiled string literals. */
  24. var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
  25. /** Used for built-in method references. */
  26. var objectProto = Object.prototype;
  27. /** Used to check objects for own properties. */
  28. var hasOwnProperty = objectProto.hasOwnProperty;
  29. /**
  30. * Creates a compiled template function that can interpolate data properties
  31. * in "interpolate" delimiters, HTML-escape interpolated data properties in
  32. * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
  33. * properties may be accessed as free variables in the template. If a setting
  34. * object is given, it takes precedence over `_.templateSettings` values.
  35. *
  36. * **Note:** In the development build `_.template` utilizes
  37. * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
  38. * for easier debugging.
  39. *
  40. * For more information on precompiling templates see
  41. * [lodash's custom builds documentation](https://lodash.com/custom-builds).
  42. *
  43. * For more information on Chrome extension sandboxes see
  44. * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
  45. *
  46. * @static
  47. * @since 0.1.0
  48. * @memberOf _
  49. * @category String
  50. * @param {string} [string=''] The template string.
  51. * @param {Object} [options={}] The options object.
  52. * @param {RegExp} [options.escape=_.templateSettings.escape]
  53. * The HTML "escape" delimiter.
  54. * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
  55. * The "evaluate" delimiter.
  56. * @param {Object} [options.imports=_.templateSettings.imports]
  57. * An object to import into the template as free variables.
  58. * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
  59. * The "interpolate" delimiter.
  60. * @param {string} [options.sourceURL='templateSources[n]']
  61. * The sourceURL of the compiled template.
  62. * @param {string} [options.variable='obj']
  63. * The data object variable name.
  64. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  65. * @returns {Function} Returns the compiled template function.
  66. * @example
  67. *
  68. * // Use the "interpolate" delimiter to create a compiled template.
  69. * var compiled = _.template('hello <%= user %>!');
  70. * compiled({ 'user': 'fred' });
  71. * // => 'hello fred!'
  72. *
  73. * // Use the HTML "escape" delimiter to escape data property values.
  74. * var compiled = _.template('<b><%- value %></b>');
  75. * compiled({ 'value': '<script>' });
  76. * // => '<b>&lt;script&gt;</b>'
  77. *
  78. * // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
  79. * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
  80. * compiled({ 'users': ['fred', 'barney'] });
  81. * // => '<li>fred</li><li>barney</li>'
  82. *
  83. * // Use the internal `print` function in "evaluate" delimiters.
  84. * var compiled = _.template('<% print("hello " + user); %>!');
  85. * compiled({ 'user': 'barney' });
  86. * // => 'hello barney!'
  87. *
  88. * // Use the ES template literal delimiter as an "interpolate" delimiter.
  89. * // Disable support by replacing the "interpolate" delimiter.
  90. * var compiled = _.template('hello ${ user }!');
  91. * compiled({ 'user': 'pebbles' });
  92. * // => 'hello pebbles!'
  93. *
  94. * // Use backslashes to treat delimiters as plain text.
  95. * var compiled = _.template('<%= "\\<%- value %\\>" %>');
  96. * compiled({ 'value': 'ignored' });
  97. * // => '<%- value %>'
  98. *
  99. * // Use the `imports` option to import `jQuery` as `jq`.
  100. * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
  101. * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
  102. * compiled({ 'users': ['fred', 'barney'] });
  103. * // => '<li>fred</li><li>barney</li>'
  104. *
  105. * // Use the `sourceURL` option to specify a custom sourceURL for the template.
  106. * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
  107. * compiled(data);
  108. * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
  109. *
  110. * // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
  111. * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
  112. * compiled.source;
  113. * // => function(data) {
  114. * // var __t, __p = '';
  115. * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
  116. * // return __p;
  117. * // }
  118. *
  119. * // Use custom template delimiters.
  120. * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
  121. * var compiled = _.template('hello {{ user }}!');
  122. * compiled({ 'user': 'mustache' });
  123. * // => 'hello mustache!'
  124. *
  125. * // Use the `source` property to inline compiled templates for meaningful
  126. * // line numbers in error messages and stack traces.
  127. * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
  128. * var JST = {\
  129. * "main": ' + _.template(mainText).source + '\
  130. * };\
  131. * ');
  132. */
  133. function template(string, options, guard) {
  134. // Based on John Resig's `tmpl` implementation
  135. // (http://ejohn.org/blog/javascript-micro-templating/)
  136. // and Laura Doktorova's doT.js (https://github.com/olado/doT).
  137. var settings = templateSettings.imports._.templateSettings || templateSettings;
  138. if (guard && isIterateeCall(string, options, guard)) {
  139. options = undefined;
  140. }
  141. string = toString(string);
  142. options = assignInWith({}, options, settings, customDefaultsAssignIn);
  143. var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn),
  144. importsKeys = keys(imports),
  145. importsValues = baseValues(imports, importsKeys);
  146. var isEscaping,
  147. isEvaluating,
  148. index = 0,
  149. interpolate = options.interpolate || reNoMatch,
  150. source = "__p += '";
  151. // Compile the regexp to match each delimiter.
  152. var reDelimiters = RegExp(
  153. (options.escape || reNoMatch).source + '|' +
  154. interpolate.source + '|' +
  155. (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
  156. (options.evaluate || reNoMatch).source + '|$'
  157. , 'g');
  158. // Use a sourceURL for easier debugging.
  159. // The sourceURL gets injected into the source that's eval-ed, so be careful
  160. // with lookup (in case of e.g. prototype pollution), and strip newlines if any.
  161. // A newline wouldn't be a valid sourceURL anyway, and it'd enable code injection.
  162. var sourceURL = hasOwnProperty.call(options, 'sourceURL')
  163. ? ('//# sourceURL=' +
  164. (options.sourceURL + '').replace(/[\r\n]/g, ' ') +
  165. '\n')
  166. : '';
  167. string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
  168. interpolateValue || (interpolateValue = esTemplateValue);
  169. // Escape characters that can't be included in string literals.
  170. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
  171. // Replace delimiters with snippets.
  172. if (escapeValue) {
  173. isEscaping = true;
  174. source += "' +\n__e(" + escapeValue + ") +\n'";
  175. }
  176. if (evaluateValue) {
  177. isEvaluating = true;
  178. source += "';\n" + evaluateValue + ";\n__p += '";
  179. }
  180. if (interpolateValue) {
  181. source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
  182. }
  183. index = offset + match.length;
  184. // The JS engine embedded in Adobe products needs `match` returned in
  185. // order to produce the correct `offset` value.
  186. return match;
  187. });
  188. source += "';\n";
  189. // If `variable` is not specified wrap a with-statement around the generated
  190. // code to add the data object to the top of the scope chain.
  191. // Like with sourceURL, we take care to not check the option's prototype,
  192. // as this configuration is a code injection vector.
  193. var variable = hasOwnProperty.call(options, 'variable') && options.variable;
  194. if (!variable) {
  195. source = 'with (obj) {\n' + source + '\n}\n';
  196. }
  197. // Cleanup code by stripping empty strings.
  198. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
  199. .replace(reEmptyStringMiddle, '$1')
  200. .replace(reEmptyStringTrailing, '$1;');
  201. // Frame code as the function body.
  202. source = 'function(' + (variable || 'obj') + ') {\n' +
  203. (variable
  204. ? ''
  205. : 'obj || (obj = {});\n'
  206. ) +
  207. "var __t, __p = ''" +
  208. (isEscaping
  209. ? ', __e = _.escape'
  210. : ''
  211. ) +
  212. (isEvaluating
  213. ? ', __j = Array.prototype.join;\n' +
  214. "function print() { __p += __j.call(arguments, '') }\n"
  215. : ';\n'
  216. ) +
  217. source +
  218. 'return __p\n}';
  219. var result = attempt(function() {
  220. return Function(importsKeys, sourceURL + 'return ' + source)
  221. .apply(undefined, importsValues);
  222. });
  223. // Provide the compiled function's source by its `toString` method or
  224. // the `source` property as a convenience for inlining compiled templates.
  225. result.source = source;
  226. if (isError(result)) {
  227. throw result;
  228. }
  229. return result;
  230. }
  231. module.exports = template;