Allow _.templateSettings to be overriden.

This commit is contained in:
Brad Dunbar
2012-04-03 17:38:39 -07:00
parent b04b813f02
commit 89c50e1a95
2 changed files with 9 additions and 6 deletions

View File

@@ -179,8 +179,11 @@ $(document).ready(function() {
}); });
test('_.templateSettings.varname', function() { test('_.templateSettings.varname', function() {
var s = '<%=data.x%>';
var data = {x: 'x'};
strictEqual(_.template(s, data, {varname: 'data'}), 'x')
_.templateSettings.varname = 'data'; _.templateSettings.varname = 'data';
strictEqual(_.template('<%=data.x%>')({x: 'x'}), 'x'); strictEqual(_.template(s)(data), 'x')
}); });
}); });

View File

@@ -951,9 +951,8 @@
// JavaScript micro-templating, similar to John Resig's implementation. // JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace, // Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code. // and correctly escapes quotes within interpolated code.
_.template = function(source, data) { _.template = function(source, data, settings) {
var settings = _.templateSettings; settings = _.extend(_.templateSettings, settings);
var varname = settings.varname || 'obj';
// Compile the template source, taking care to escape characters that // Compile the template source, taking care to escape characters that
// cannot be included in a string literal and then unescape them in code // cannot be included in a string literal and then unescape them in code
@@ -978,7 +977,7 @@
compiled = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};\n' + compiled = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};\n' +
compiled + "return __p.join('');\n"; compiled + "return __p.join('');\n";
var render = new Function(varname, '_', compiled); var render = new Function(settings.varname || 'obj', '_', compiled);
if (data) return render(data, _); if (data) return render(data, _);
var template = function(data) { var template = function(data) {
return render.call(this, data, _); return render.call(this, data, _);
@@ -986,7 +985,8 @@
// Provide the compiled function source as a convenience for build time // Provide the compiled function source as a convenience for build time
// precompilation. // precompilation.
template.compiled = 'function(' + varname + '){\n' + compiled + '\n}'; template.compiled = 'function(' + (settings.varname || 'obj') + '){\n' +
compiled + '\n}';
return template; return template;
}; };