template.js 8.9 KB

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