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');
13 /** Used to match empty string literals in compiled template source. */
14 var reEmptyStringLeading = /\b__p \+= '';/g,
15 reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
16 reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
20 * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
22 var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
24 /** Used to ensure capturing order of template delimiters. */
25 var reNoMatch = /($^)/;
27 /** Used to match unescaped characters in compiled string literals. */
28 var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
30 /** Used for built-in method references. */
31 var objectProto = Object.prototype;
33 /** Used to check objects for own properties. */
34 var hasOwnProperty = objectProto.hasOwnProperty;
37 * Creates a compiled template function that can interpolate data properties
38 * in "interpolate" delimiters, HTML-escape interpolated data properties in
39 * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
40 * properties may be accessed as free variables in the template. If a setting
41 * object is given, it takes precedence over `_.templateSettings` values.
43 * **Note:** In the development build `_.template` utilizes
44 * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
45 * for easier debugging.
47 * For more information on precompiling templates see
48 * [lodash's custom builds documentation](https://lodash.com/custom-builds).
50 * For more information on Chrome extension sandboxes see
51 * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
57 * @param {string} [string=''] The template string.
58 * @param {Object} [options={}] The options object.
59 * @param {RegExp} [options.escape=_.templateSettings.escape]
60 * The HTML "escape" delimiter.
61 * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
62 * The "evaluate" delimiter.
63 * @param {Object} [options.imports=_.templateSettings.imports]
64 * An object to import into the template as free variables.
65 * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
66 * The "interpolate" delimiter.
67 * @param {string} [options.sourceURL='templateSources[n]']
68 * The sourceURL of the compiled template.
69 * @param {string} [options.variable='obj']
70 * The data object variable name.
71 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
72 * @returns {Function} Returns the compiled template function.
75 * // Use the "interpolate" delimiter to create a compiled template.
76 * var compiled = _.template('hello <%= user %>!');
77 * compiled({ 'user': 'fred' });
80 * // Use the HTML "escape" delimiter to escape data property values.
81 * var compiled = _.template('<b><%- value %></b>');
82 * compiled({ 'value': '<script>' });
83 * // => '<b><script></b>'
85 * // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
86 * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
87 * compiled({ 'users': ['fred', 'barney'] });
88 * // => '<li>fred</li><li>barney</li>'
90 * // Use the internal `print` function in "evaluate" delimiters.
91 * var compiled = _.template('<% print("hello " + user); %>!');
92 * compiled({ 'user': 'barney' });
93 * // => 'hello barney!'
95 * // Use the ES template literal delimiter as an "interpolate" delimiter.
96 * // Disable support by replacing the "interpolate" delimiter.
97 * var compiled = _.template('hello ${ user }!');
98 * compiled({ 'user': 'pebbles' });
99 * // => 'hello pebbles!'
101 * // Use backslashes to treat delimiters as plain text.
102 * var compiled = _.template('<%= "\\<%- value %\\>" %>');
103 * compiled({ 'value': 'ignored' });
104 * // => '<%- value %>'
106 * // Use the `imports` option to import `jQuery` as `jq`.
107 * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
108 * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
109 * compiled({ 'users': ['fred', 'barney'] });
110 * // => '<li>fred</li><li>barney</li>'
112 * // Use the `sourceURL` option to specify a custom sourceURL for the template.
113 * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
115 * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
117 * // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
118 * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
120 * // => function(data) {
121 * // var __t, __p = '';
122 * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
126 * // Use custom template delimiters.
127 * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
128 * var compiled = _.template('hello {{ user }}!');
129 * compiled({ 'user': 'mustache' });
130 * // => 'hello mustache!'
132 * // Use the `source` property to inline compiled templates for meaningful
133 * // line numbers in error messages and stack traces.
134 * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
136 * "main": ' + _.template(mainText).source + '\
140 function template(string, options, guard) {
141 // Based on John Resig's `tmpl` implementation
142 // (http://ejohn.org/blog/javascript-micro-templating/)
143 // and Laura Doktorova's doT.js (https://github.com/olado/doT).
144 var settings = templateSettings.imports._.templateSettings || templateSettings;
146 if (guard && isIterateeCall(string, options, guard)) {
149 string = toString(string);
150 options = assignInWith({}, options, settings, customDefaultsAssignIn);
152 var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn),
153 importsKeys = keys(imports),
154 importsValues = baseValues(imports, importsKeys);
159 interpolate = options.interpolate || reNoMatch,
162 // Compile the regexp to match each delimiter.
163 var reDelimiters = RegExp(
164 (options.escape || reNoMatch).source + '|' +
165 interpolate.source + '|' +
166 (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
167 (options.evaluate || reNoMatch).source + '|$'
170 // Use a sourceURL for easier debugging.
171 // The sourceURL gets injected into the source that's eval-ed, so be careful
172 // to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in
173 // and escape the comment, thus injecting code that gets evaled.
174 var sourceURL = hasOwnProperty.call(options, 'sourceURL')
175 ? ('//# sourceURL=' +
176 (options.sourceURL + '').replace(/\s/g, ' ') +
180 string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
181 interpolateValue || (interpolateValue = esTemplateValue);
183 // Escape characters that can't be included in string literals.
184 source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
186 // Replace delimiters with snippets.
189 source += "' +\n__e(" + escapeValue + ") +\n'";
193 source += "';\n" + evaluateValue + ";\n__p += '";
195 if (interpolateValue) {
196 source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
198 index = offset + match.length;
200 // The JS engine embedded in Adobe products needs `match` returned in
201 // order to produce the correct `offset` value.
207 // If `variable` is not specified wrap a with-statement around the generated
208 // code to add the data object to the top of the scope chain.
209 var variable = hasOwnProperty.call(options, 'variable') && options.variable;
211 source = 'with (obj) {\n' + source + '\n}\n';
213 // Cleanup code by stripping empty strings.
214 source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
215 .replace(reEmptyStringMiddle, '$1')
216 .replace(reEmptyStringTrailing, '$1;');
218 // Frame code as the function body.
219 source = 'function(' + (variable || 'obj') + ') {\n' +
222 : 'obj || (obj = {});\n'
224 "var __t, __p = ''" +
230 ? ', __j = Array.prototype.join;\n' +
231 "function print() { __p += __j.call(arguments, '') }\n"
237 var result = attempt(function() {
238 return Function(importsKeys, sourceURL + 'return ' + source)
239 .apply(undefined, importsValues);
242 // Provide the compiled function's source by its `toString` method or
243 // the `source` property as a convenience for inlining compiled templates.
244 result.source = source;
245 if (isError(result)) {
251 module.exports = template;