UNPKG

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