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');
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;
18 /** Used to match [ES template delimiters](http://ecma-international.org/ecma-262/6.0/#sec-template-literal-lexical-components). */
19 var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
21 /** Used to ensure capturing order of template delimiters. */
22 var reNoMatch = /($^)/;
24 /** Used to match unescaped characters in compiled string literals. */
25 var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
28 * Creates a compiled template function that can interpolate data properties
29 * in "interpolate" delimiters, HTML-escape interpolated data properties in
30 * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
31 * properties may be accessed as free variables in the template. If a setting
32 * object is given it takes precedence over `_.templateSettings` values.
34 * **Note:** In the development build `_.template` utilizes
35 * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
36 * for easier debugging.
38 * For more information on precompiling templates see
39 * [lodash's custom builds documentation](https://lodash.com/custom-builds).
41 * For more information on Chrome extension sandboxes see
42 * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
47 * @param {string} [string=''] The template string.
48 * @param {Object} [options] The options object.
49 * @param {RegExp} [options.escape] The HTML "escape" delimiter.
50 * @param {RegExp} [options.evaluate] The "evaluate" delimiter.
51 * @param {Object} [options.imports] An object to import into the template as free variables.
52 * @param {RegExp} [options.interpolate] The "interpolate" delimiter.
53 * @param {string} [options.sourceURL] The sourceURL of the template's compiled source.
54 * @param {string} [options.variable] The data object variable name.
55 * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`.
56 * @returns {Function} Returns the compiled template function.
59 * // Use the "interpolate" delimiter to create a compiled template.
60 * var compiled = _.template('hello <%= user %>!');
61 * compiled({ 'user': 'fred' });
64 * // Use the HTML "escape" delimiter to escape data property values.
65 * var compiled = _.template('<b><%- value %></b>');
66 * compiled({ 'value': '<script>' });
67 * // => '<b><script></b>'
69 * // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
70 * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
71 * compiled({ 'users': ['fred', 'barney'] });
72 * // => '<li>fred</li><li>barney</li>'
74 * // Use the internal `print` function in "evaluate" delimiters.
75 * var compiled = _.template('<% print("hello " + user); %>!');
76 * compiled({ 'user': 'barney' });
77 * // => 'hello barney!'
79 * // Use the ES delimiter as an alternative to the default "interpolate" delimiter.
80 * var compiled = _.template('hello ${ user }!');
81 * compiled({ 'user': 'pebbles' });
82 * // => 'hello pebbles!'
84 * // Use custom template delimiters.
85 * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
86 * var compiled = _.template('hello {{ user }}!');
87 * compiled({ 'user': 'mustache' });
88 * // => 'hello mustache!'
90 * // Use backslashes to treat delimiters as plain text.
91 * var compiled = _.template('<%= "\\<%- value %\\>" %>');
92 * compiled({ 'value': 'ignored' });
93 * // => '<%- value %>'
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>'
101 * // Use the `sourceURL` option to specify a custom sourceURL for the template.
102 * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
104 * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
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' });
109 * // => function(data) {
110 * // var __t, __p = '';
111 * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
115 * // Use the `source` property to inline compiled templates for meaningful
116 * // line numbers in error messages and stack traces.
117 * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
119 * "main": ' + _.template(mainText).source + '\
123 function template(string, options, guard) {
124 // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/)
125 // and Laura Doktorova's doT.js (https://github.com/olado/doT).
126 var settings = templateSettings.imports._.templateSettings || templateSettings;
128 if (guard && isIterateeCall(string, options, guard)) {
131 string = toString(string);
132 options = assignInWith({}, options, settings, assignInDefaults);
134 var imports = assignInWith({}, options.imports, settings.imports, assignInDefaults),
135 importsKeys = keys(imports),
136 importsValues = baseValues(imports, importsKeys);
141 interpolate = options.interpolate || reNoMatch,
144 // Compile the regexp to match each delimiter.
145 var reDelimiters = RegExp(
146 (options.escape || reNoMatch).source + '|' +
147 interpolate.source + '|' +
148 (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
149 (options.evaluate || reNoMatch).source + '|$'
152 // Use a sourceURL for easier debugging.
153 var sourceURL = 'sourceURL' in options ? '//# sourceURL=' + options.sourceURL + '\n' : '';
155 string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
156 interpolateValue || (interpolateValue = esTemplateValue);
158 // Escape characters that can't be included in string literals.
159 source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
161 // Replace delimiters with snippets.
164 source += "' +\n__e(" + escapeValue + ") +\n'";
168 source += "';\n" + evaluateValue + ";\n__p += '";
170 if (interpolateValue) {
171 source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
173 index = offset + match.length;
175 // The JS engine embedded in Adobe products needs `match` returned in
176 // order to produce the correct `offset` value.
182 // If `variable` is not specified wrap a with-statement around the generated
183 // code to add the data object to the top of the scope chain.
184 var variable = options.variable;
186 source = 'with (obj) {\n' + source + '\n}\n';
188 // Cleanup code by stripping empty strings.
189 source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
190 .replace(reEmptyStringMiddle, '$1')
191 .replace(reEmptyStringTrailing, '$1;');
193 // Frame code as the function body.
194 source = 'function(' + (variable || 'obj') + ') {\n' +
197 : 'obj || (obj = {});\n'
199 "var __t, __p = ''" +
205 ? ', __j = Array.prototype.join;\n' +
206 "function print() { __p += __j.call(arguments, '') }\n"
212 var result = attempt(function() {
213 return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
216 // Provide the compiled function's source by its `toString` method or
217 // the `source` property as a convenience for inlining compiled templates.
218 result.source = source;
219 if (isError(result)) {
225 module.exports = template;