Add "imports" option to _.templateSettings. [closes #148]

Former-commit-id: 16a019d27aea2e7a72665f62adf4c4c35e29b4bf
This commit is contained in:
John-David Dalton
2012-12-30 12:18:32 -06:00
parent 7fdf00d5e9
commit a14be3a42c
8 changed files with 242 additions and 158 deletions

View File

@@ -351,6 +351,7 @@
object = { 'a': 1, 'b': 2, 'c': 3 },
noop = function() {},
string = 'abc',
template = '<%= a %>',
func = lodash[methodName];
try {
@@ -442,6 +443,9 @@
else if (utilityMethods.indexOf(methodName) > -1) {
if (methodName == 'result') {
func(object, 'b');
} else if (methodName == 'template') {
func(template, object);
func(template, null, { 'imports': object })(object);
} else if (methodName == 'times') {
func(2, noop, object);
} else {
@@ -765,6 +769,7 @@
ok(lodash.some([false, true, false]), '_.some: ' + basename);
equal(lodash.template('${a}', object), '${a}', '_.template should ignore ES6 delimiters: ' + basename);
equal('imports' in lodash.templateSettings, false, '_.templateSettings should not have an "imports" property: ' + basename);
equal(lodash.uniqueId(0), '1', '_.uniqueId should ignore a prefix of `0`: ' + basename);
start();

View File

@@ -1768,20 +1768,25 @@
});
test('should tokenize delimiters', function() {
var compiled = _.template('<span class="icon-<%= type %>2"></span>');
equal(compiled({ 'type': 1 }), '<span class="icon-12"></span>');
var compiled = _.template('<span class="icon-<%= type %>2"></span>'),
data = { 'type': 1 };
equal(compiled(data), '<span class="icon-12"></span>');
});
test('should work with "interpolate" delimiters containing ternary operators', function() {
var compiled = _.template('<%= value ? value : "b" %>');
equal(compiled({ 'value': 'a' }), 'a');
var compiled = _.template('<%= value ? value : "b" %>'),
data = { 'value': 'a' };
equal(compiled(data), 'a');
});
test('should parse delimiters with newlines', function() {
var expected = '<<\nprint("<p>" + (value ? "yes" : "no") + "</p>")\n>>',
compiled = _.template(expected, null, { 'evaluate': /<<(.+?)>>/g });
compiled = _.template(expected, null, { 'evaluate': /<<(.+?)>>/g }),
data = { 'value': true };
equal(compiled({ 'value': true }), expected);
equal(compiled(data), expected);
});
test('should parse ES6 template delimiters', function() {
@@ -1789,6 +1794,13 @@
equal(_.template('1${value}3', data), '123');
equal(_.template('${"{" + value + "\\}"}', data), '{2}');
});
test('supports the "imports" option', function() {
var options = { 'imports': { 'a': 1 } },
compiled = _.template('<%= a %>', null, options);
equal(compiled({}), '1');
});
}());
/*--------------------------------------------------------------------------*/