template.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. var assignInDefaults = require('./_assignInDefaults'),
  2. assignInWith = require('./assignInWith'),
  3. attempt = require('./attempt'),
  4. baseValues = require('./_baseValues'),
  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/6.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 delimiter as an alternative to the default "interpolate" delimiter.
  85. * var compiled = _.template('hello ${ user }!');
  86. * compiled({ 'user': 'pebbles' });
  87. * // => 'hello pebbles!'
  88. *
  89. * // Use backslashes to treat delimiters as plain text.
  90. * var compiled = _.template('<%= "\\<%- value %\\>" %>');
  91. * compiled({ 'value': 'ignored' });
  92. * // => '<%- value %>'
  93. *
  94. * // Use the `imports` option to import `jQuery` as `jq`.
  95. * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
  96. * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
  97. * compiled({ 'users': ['fred', 'barney'] });
  98. * // => '<li>fred</li><li>barney</li>'
  99. *
  100. * // Use the `sourceURL` option to specify a custom sourceURL for the template.
  101. * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
  102. * compiled(data);
  103. * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
  104. *
  105. * // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
  106. * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
  107. * compiled.source;
  108. * // => function(data) {
  109. * // var __t, __p = '';
  110. * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
  111. * // return __p;
  112. * // }
  113. *
  114. * // Use custom template delimiters.
  115. * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
  116. * var compiled = _.template('hello {{ user }}!');
  117. * compiled({ 'user': 'mustache' });
  118. * // => 'hello mustache!'
  119. *
  120. * // Use the `source` property to inline compiled templates for meaningful
  121. * // line numbers in error messages and stack traces.
  122. * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
  123. * var JST = {\
  124. * "main": ' + _.template(mainText).source + '\
  125. * };\
  126. * ');
  127. */
  128. function template(string, options, guard) {
  129. // Based on John Resig's `tmpl` implementation
  130. // (http://ejohn.org/blog/javascript-micro-templating/)
  131. // and Laura Doktorova's doT.js (https://github.com/olado/doT).
  132. var settings = templateSettings.imports._.templateSettings || templateSettings;
  133. if (guard && isIterateeCall(string, options, guard)) {
  134. options = undefined;
  135. }
  136. string = toString(string);
  137. options = assignInWith({}, options, settings, assignInDefaults);
  138. var imports = assignInWith({}, options.imports, settings.imports, assignInDefaults),
  139. importsKeys = keys(imports),
  140. importsValues = baseValues(imports, importsKeys);
  141. var isEscaping,
  142. isEvaluating,
  143. index = 0,
  144. interpolate = options.interpolate || reNoMatch,
  145. source = "__p += '";
  146. // Compile the regexp to match each delimiter.
  147. var reDelimiters = RegExp(
  148. (options.escape || reNoMatch).source + '|' +
  149. interpolate.source + '|' +
  150. (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
  151. (options.evaluate || reNoMatch).source + '|$'
  152. , 'g');
  153. // Use a sourceURL for easier debugging.
  154. var sourceURL = 'sourceURL' in options ? '//# sourceURL=' + options.sourceURL + '\n' : '';
  155. string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
  156. interpolateValue || (interpolateValue = esTemplateValue);
  157. // Escape characters that can't be included in string literals.
  158. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
  159. // Replace delimiters with snippets.
  160. if (escapeValue) {
  161. isEscaping = true;
  162. source += "' +\n__e(" + escapeValue + ") +\n'";
  163. }
  164. if (evaluateValue) {
  165. isEvaluating = true;
  166. source += "';\n" + evaluateValue + ";\n__p += '";
  167. }
  168. if (interpolateValue) {
  169. source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
  170. }
  171. index = offset + match.length;
  172. // The JS engine embedded in Adobe products needs `match` returned in
  173. // order to produce the correct `offset` value.
  174. return match;
  175. });
  176. source += "';\n";
  177. // If `variable` is not specified wrap a with-statement around the generated
  178. // code to add the data object to the top of the scope chain.
  179. var variable = options.variable;
  180. if (!variable) {
  181. source = 'with (obj) {\n' + source + '\n}\n';
  182. }
  183. // Cleanup code by stripping empty strings.
  184. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
  185. .replace(reEmptyStringMiddle, '$1')
  186. .replace(reEmptyStringTrailing, '$1;');
  187. // Frame code as the function body.
  188. source = 'function(' + (variable || 'obj') + ') {\n' +
  189. (variable
  190. ? ''
  191. : 'obj || (obj = {});\n'
  192. ) +
  193. "var __t, __p = ''" +
  194. (isEscaping
  195. ? ', __e = _.escape'
  196. : ''
  197. ) +
  198. (isEvaluating
  199. ? ', __j = Array.prototype.join;\n' +
  200. "function print() { __p += __j.call(arguments, '') }\n"
  201. : ';\n'
  202. ) +
  203. source +
  204. 'return __p\n}';
  205. var result = attempt(function() {
  206. return Function(importsKeys, sourceURL + 'return ' + source)
  207. .apply(undefined, importsValues);
  208. });
  209. // Provide the compiled function's source by its `toString` method or
  210. // the `source` property as a convenience for inlining compiled templates.
  211. result.source = source;
  212. if (isError(result)) {
  213. throw result;
  214. }
  215. return result;
  216. }
  217. module.exports = template;