template.js 10 KB

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