123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- var defaults = require('./defaults.js');
- var underscore = require('./underscore.js');
- require('./templateSettings.js');
- var noMatch = /(.)^/;
- var escapes = {
- "'": "'",
- '\\': '\\',
- '\r': 'r',
- '\n': 'n',
- '\u2028': 'u2028',
- '\u2029': 'u2029'
- };
- var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
- function escapeChar(match) {
- return '\\' + escapes[match];
- }
- var bareIdentifier = /^\s*(\w|\$)+\s*$/;
- function template(text, settings, oldSettings) {
- if (!settings && oldSettings) settings = oldSettings;
- settings = defaults({}, settings, underscore.templateSettings);
-
- var matcher = RegExp([
- (settings.escape || noMatch).source,
- (settings.interpolate || noMatch).source,
- (settings.evaluate || noMatch).source
- ].join('|') + '|$', 'g');
-
- var index = 0;
- var source = "__p+='";
- text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
- source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
- index = offset + match.length;
- if (escape) {
- source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
- } else if (interpolate) {
- source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
- } else if (evaluate) {
- source += "';\n" + evaluate + "\n__p+='";
- }
-
- return match;
- });
- source += "';\n";
- var argument = settings.variable;
- if (argument) {
-
- if (!bareIdentifier.test(argument)) throw new Error(
- 'variable is not a bare identifier: ' + argument
- );
- } else {
-
- source = 'with(obj||{}){\n' + source + '}\n';
- argument = 'obj';
- }
- source = "var __t,__p='',__j=Array.prototype.join," +
- "print=function(){__p+=__j.call(arguments,'');};\n" +
- source + 'return __p;\n';
- var render;
- try {
- render = new Function(argument, '_', source);
- } catch (e) {
- e.source = source;
- throw e;
- }
- var template = function(data) {
- return render.call(this, data, underscore);
- };
-
- template.source = 'function(' + argument + '){\n' + source + '}';
- return template;
- }
- module.exports = template;
|