2 * lodash 3.6.2 (Custom Build) <https://lodash.com/>
3 * Build: `lodash modern modularize exports="npm" -o ./`
4 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
5 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
6 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
7 * Available under MIT license <https://lodash.com/license>
9 var baseCopy = require('lodash._basecopy'),
10 baseToString = require('lodash._basetostring'),
11 baseValues = require('lodash._basevalues'),
12 isIterateeCall = require('lodash._isiterateecall'),
13 reInterpolate = require('lodash._reinterpolate'),
14 keys = require('lodash.keys'),
15 restParam = require('lodash.restparam'),
16 templateSettings = require('lodash.templatesettings');
18 /** `Object#toString` result references. */
19 var errorTag = '[object Error]';
21 /** Used to match empty string literals in compiled template source. */
22 var reEmptyStringLeading = /\b__p \+= '';/g,
23 reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
24 reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
26 /** Used to match [ES template delimiters](http://ecma-international.org/ecma-262/6.0/#sec-template-literal-lexical-components). */
27 var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
29 /** Used to ensure capturing order of template delimiters. */
30 var reNoMatch = /($^)/;
32 /** Used to match unescaped characters in compiled string literals. */
33 var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
35 /** Used to escape characters for inclusion in compiled string literals. */
46 * Used by `_.template` to escape characters for inclusion in compiled string literals.
49 * @param {string} chr The matched character to escape.
50 * @returns {string} Returns the escaped character.
52 function escapeStringChar(chr) {
53 return '\\' + stringEscapes[chr];
57 * Checks if `value` is object-like.
60 * @param {*} value The value to check.
61 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
63 function isObjectLike(value) {
64 return !!value && typeof value == 'object';
67 /** Used for native method references. */
68 var objectProto = Object.prototype;
70 /** Used to check objects for own properties. */
71 var hasOwnProperty = objectProto.hasOwnProperty;
74 * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
77 var objToString = objectProto.toString;
80 * Used by `_.template` to customize its `_.assign` use.
82 * **Note:** This function is like `assignDefaults` except that it ignores
83 * inherited property values when checking if a property is `undefined`.
86 * @param {*} objectValue The destination object property value.
87 * @param {*} sourceValue The source object property value.
88 * @param {string} key The key associated with the object and source values.
89 * @param {Object} object The destination object.
90 * @returns {*} Returns the value to assign to the destination object.
92 function assignOwnDefaults(objectValue, sourceValue, key, object) {
93 return (objectValue === undefined || !hasOwnProperty.call(object, key))
99 * A specialized version of `_.assign` for customizing assigned values without
100 * support for argument juggling, multiple sources, and `this` binding `customizer`
104 * @param {Object} object The destination object.
105 * @param {Object} source The source object.
106 * @param {Function} customizer The function to customize assigned values.
107 * @returns {Object} Returns `object`.
109 function assignWith(object, source, customizer) {
111 props = keys(source),
112 length = props.length;
114 while (++index < length) {
115 var key = props[index],
117 result = customizer(value, source[key], key, object, source);
119 if ((result === result ? (result !== value) : (value === value)) ||
120 (value === undefined && !(key in object))) {
121 object[key] = result;
128 * The base implementation of `_.assign` without support for argument juggling,
129 * multiple sources, and `customizer` functions.
132 * @param {Object} object The destination object.
133 * @param {Object} source The source object.
134 * @returns {Object} Returns `object`.
136 function baseAssign(object, source) {
137 return source == null
139 : baseCopy(source, keys(source), object);
143 * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
144 * `SyntaxError`, `TypeError`, or `URIError` object.
149 * @param {*} value The value to check.
150 * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
153 * _.isError(new Error);
159 function isError(value) {
160 return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag;
164 * Creates a compiled template function that can interpolate data properties
165 * in "interpolate" delimiters, HTML-escape interpolated data properties in
166 * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
167 * properties may be accessed as free variables in the template. If a setting
168 * object is provided it takes precedence over `_.templateSettings` values.
170 * **Note:** In the development build `_.template` utilizes
171 * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
172 * for easier debugging.
174 * For more information on precompiling templates see
175 * [lodash's custom builds documentation](https://lodash.com/custom-builds).
177 * For more information on Chrome extension sandboxes see
178 * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
183 * @param {string} [string=''] The template string.
184 * @param {Object} [options] The options object.
185 * @param {RegExp} [options.escape] The HTML "escape" delimiter.
186 * @param {RegExp} [options.evaluate] The "evaluate" delimiter.
187 * @param {Object} [options.imports] An object to import into the template as free variables.
188 * @param {RegExp} [options.interpolate] The "interpolate" delimiter.
189 * @param {string} [options.sourceURL] The sourceURL of the template's compiled source.
190 * @param {string} [options.variable] The data object variable name.
191 * @param- {Object} [otherOptions] Enables the legacy `options` param signature.
192 * @returns {Function} Returns the compiled template function.
195 * // using the "interpolate" delimiter to create a compiled template
196 * var compiled = _.template('hello <%= user %>!');
197 * compiled({ 'user': 'fred' });
198 * // => 'hello fred!'
200 * // using the HTML "escape" delimiter to escape data property values
201 * var compiled = _.template('<b><%- value %></b>');
202 * compiled({ 'value': '<script>' });
203 * // => '<b><script></b>'
205 * // using the "evaluate" delimiter to execute JavaScript and generate HTML
206 * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
207 * compiled({ 'users': ['fred', 'barney'] });
208 * // => '<li>fred</li><li>barney</li>'
210 * // using the internal `print` function in "evaluate" delimiters
211 * var compiled = _.template('<% print("hello " + user); %>!');
212 * compiled({ 'user': 'barney' });
213 * // => 'hello barney!'
215 * // using the ES delimiter as an alternative to the default "interpolate" delimiter
216 * var compiled = _.template('hello ${ user }!');
217 * compiled({ 'user': 'pebbles' });
218 * // => 'hello pebbles!'
220 * // using custom template delimiters
221 * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
222 * var compiled = _.template('hello {{ user }}!');
223 * compiled({ 'user': 'mustache' });
224 * // => 'hello mustache!'
226 * // using backslashes to treat delimiters as plain text
227 * var compiled = _.template('<%= "\\<%- value %\\>" %>');
228 * compiled({ 'value': 'ignored' });
229 * // => '<%- value %>'
231 * // using the `imports` option to import `jQuery` as `jq`
232 * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
233 * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
234 * compiled({ 'users': ['fred', 'barney'] });
235 * // => '<li>fred</li><li>barney</li>'
237 * // using the `sourceURL` option to specify a custom sourceURL for the template
238 * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
240 * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
242 * // using the `variable` option to ensure a with-statement isn't used in the compiled template
243 * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
245 * // => function(data) {
246 * // var __t, __p = '';
247 * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
251 * // using the `source` property to inline compiled templates for meaningful
252 * // line numbers in error messages and a stack trace
253 * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
255 * "main": ' + _.template(mainText).source + '\
259 function template(string, options, otherOptions) {
260 // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/)
261 // and Laura Doktorova's doT.js (https://github.com/olado/doT).
262 var settings = templateSettings.imports._.templateSettings || templateSettings;
264 if (otherOptions && isIterateeCall(string, options, otherOptions)) {
265 options = otherOptions = undefined;
267 string = baseToString(string);
268 options = assignWith(baseAssign({}, otherOptions || options), settings, assignOwnDefaults);
270 var imports = assignWith(baseAssign({}, options.imports), settings.imports, assignOwnDefaults),
271 importsKeys = keys(imports),
272 importsValues = baseValues(imports, importsKeys);
277 interpolate = options.interpolate || reNoMatch,
280 // Compile the regexp to match each delimiter.
281 var reDelimiters = RegExp(
282 (options.escape || reNoMatch).source + '|' +
283 interpolate.source + '|' +
284 (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
285 (options.evaluate || reNoMatch).source + '|$'
288 // Use a sourceURL for easier debugging.
289 var sourceURL = 'sourceURL' in options ? '//# sourceURL=' + options.sourceURL + '\n' : '';
291 string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
292 interpolateValue || (interpolateValue = esTemplateValue);
294 // Escape characters that can't be included in string literals.
295 source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
297 // Replace delimiters with snippets.
300 source += "' +\n__e(" + escapeValue + ") +\n'";
304 source += "';\n" + evaluateValue + ";\n__p += '";
306 if (interpolateValue) {
307 source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
309 index = offset + match.length;
311 // The JS engine embedded in Adobe products requires returning the `match`
312 // string in order to produce the correct `offset` value.
318 // If `variable` is not specified wrap a with-statement around the generated
319 // code to add the data object to the top of the scope chain.
320 var variable = options.variable;
322 source = 'with (obj) {\n' + source + '\n}\n';
324 // Cleanup code by stripping empty strings.
325 source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
326 .replace(reEmptyStringMiddle, '$1')
327 .replace(reEmptyStringTrailing, '$1;');
329 // Frame code as the function body.
330 source = 'function(' + (variable || 'obj') + ') {\n' +
333 : 'obj || (obj = {});\n'
335 "var __t, __p = ''" +
341 ? ', __j = Array.prototype.join;\n' +
342 "function print() { __p += __j.call(arguments, '') }\n"
348 var result = attempt(function() {
349 return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
352 // Provide the compiled function's source by its `toString` method or
353 // the `source` property as a convenience for inlining compiled templates.
354 result.source = source;
355 if (isError(result)) {
362 * Attempts to invoke `func`, returning either the result or the caught error
363 * object. Any additional arguments are provided to `func` when it is invoked.
368 * @param {Function} func The function to attempt.
369 * @returns {*} Returns the `func` result or error object.
372 * // avoid throwing errors for invalid selectors
373 * var elements = _.attempt(function(selector) {
374 * return document.querySelectorAll(selector);
377 * if (_.isError(elements)) {
381 var attempt = restParam(function(func, args) {
383 return func.apply(undefined, args);
385 return isError(e) ? e : new Error(e);
389 module.exports = template;