UNPKG

9.81 kBJavaScriptView Raw
1var 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
13/** Used to match empty string literals in compiled template source. */
14var reEmptyStringLeading = /\b__p \+= '';/g,
15 reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
16 reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
17
18/**
19 * Used to match
20 * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
21 */
22var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
23
24/** Used to ensure capturing order of template delimiters. */
25var reNoMatch = /($^)/;
26
27/** Used to match unescaped characters in compiled string literals. */
28var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
29
30/** Used for built-in method references. */
31var objectProto = Object.prototype;
32
33/** Used to check objects for own properties. */
34var hasOwnProperty = objectProto.hasOwnProperty;
35
36/**
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.
42 *
43 * **Note:** In the development build `_.template` utilizes
44 * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
45 * for easier debugging.
46 *
47 * For more information on precompiling templates see
48 * [lodash's custom builds documentation](https://lodash.com/custom-builds).
49 *
50 * For more information on Chrome extension sandboxes see
51 * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
52 *
53 * @static
54 * @since 0.1.0
55 * @memberOf _
56 * @category String
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.
73 * @example
74 *
75 * // Use the "interpolate" delimiter to create a compiled template.
76 * var compiled = _.template('hello <%= user %>!');
77 * compiled({ 'user': 'fred' });
78 * // => 'hello fred!'
79 *
80 * // Use the HTML "escape" delimiter to escape data property values.
81 * var compiled = _.template('<b><%- value %></b>');
82 * compiled({ 'value': '<script>' });
83 * // => '<b>&lt;script&gt;</b>'
84 *
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>'
89 *
90 * // Use the internal `print` function in "evaluate" delimiters.
91 * var compiled = _.template('<% print("hello " + user); %>!');
92 * compiled({ 'user': 'barney' });
93 * // => 'hello barney!'
94 *
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!'
100 *
101 * // Use backslashes to treat delimiters as plain text.
102 * var compiled = _.template('<%= "\\<%- value %\\>" %>');
103 * compiled({ 'value': 'ignored' });
104 * // => '<%- value %>'
105 *
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>'
111 *
112 * // Use the `sourceURL` option to specify a custom sourceURL for the template.
113 * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
114 * compiled(data);
115 * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
116 *
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' });
119 * compiled.source;
120 * // => function(data) {
121 * // var __t, __p = '';
122 * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
123 * // return __p;
124 * // }
125 *
126 * // Use custom template delimiters.
127 * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
128 * var compiled = _.template('hello {{ user }}!');
129 * compiled({ 'user': 'mustache' });
130 * // => 'hello mustache!'
131 *
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'), '\
135 * var JST = {\
136 * "main": ' + _.template(mainText).source + '\
137 * };\
138 * ');
139 */
140function 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;
145
146 if (guard && isIterateeCall(string, options, guard)) {
147 options = undefined;
148 }
149 string = toString(string);
150 options = assignInWith({}, options, settings, customDefaultsAssignIn);
151
152 var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn),
153 importsKeys = keys(imports),
154 importsValues = baseValues(imports, importsKeys);
155
156 var isEscaping,
157 isEvaluating,
158 index = 0,
159 interpolate = options.interpolate || reNoMatch,
160 source = "__p += '";
161
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 + '|$'
168 , 'g');
169
170 // Use a sourceURL for easier debugging.
171 // The sourceURL gets injected into the source that's eval-ed, so be careful
172 // with lookup (in case of e.g. prototype pollution), and strip newlines if any.
173 // A newline wouldn't be a valid sourceURL anyway, and it'd enable code injection.
174 var sourceURL = hasOwnProperty.call(options, 'sourceURL')
175 ? ('//# sourceURL=' +
176 (options.sourceURL + '').replace(/[\r\n]/g, ' ') +
177 '\n')
178 : '';
179
180 string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
181 interpolateValue || (interpolateValue = esTemplateValue);
182
183 // Escape characters that can't be included in string literals.
184 source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
185
186 // Replace delimiters with snippets.
187 if (escapeValue) {
188 isEscaping = true;
189 source += "' +\n__e(" + escapeValue + ") +\n'";
190 }
191 if (evaluateValue) {
192 isEvaluating = true;
193 source += "';\n" + evaluateValue + ";\n__p += '";
194 }
195 if (interpolateValue) {
196 source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
197 }
198 index = offset + match.length;
199
200 // The JS engine embedded in Adobe products needs `match` returned in
201 // order to produce the correct `offset` value.
202 return match;
203 });
204
205 source += "';\n";
206
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 // Like with sourceURL, we take care to not check the option's prototype,
210 // as this configuration is a code injection vector.
211 var variable = hasOwnProperty.call(options, 'variable') && options.variable;
212 if (!variable) {
213 source = 'with (obj) {\n' + source + '\n}\n';
214 }
215 // Cleanup code by stripping empty strings.
216 source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
217 .replace(reEmptyStringMiddle, '$1')
218 .replace(reEmptyStringTrailing, '$1;');
219
220 // Frame code as the function body.
221 source = 'function(' + (variable || 'obj') + ') {\n' +
222 (variable
223 ? ''
224 : 'obj || (obj = {});\n'
225 ) +
226 "var __t, __p = ''" +
227 (isEscaping
228 ? ', __e = _.escape'
229 : ''
230 ) +
231 (isEvaluating
232 ? ', __j = Array.prototype.join;\n' +
233 "function print() { __p += __j.call(arguments, '') }\n"
234 : ';\n'
235 ) +
236 source +
237 'return __p\n}';
238
239 var result = attempt(function() {
240 return Function(importsKeys, sourceURL + 'return ' + source)
241 .apply(undefined, importsValues);
242 });
243
244 // Provide the compiled function's source by its `toString` method or
245 // the `source` property as a convenience for inlining compiled templates.
246 result.source = source;
247 if (isError(result)) {
248 throw result;
249 }
250 return result;
251}
252
253module.exports = template;