template.js 11 KB

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