* 'interpolation' of https://github.com/calvinmetcalf/Leaflet:
  '#1968 compiled interpolation'
This commit is contained in:
Vladimir Agafonkin 2013-08-27 21:28:38 +03:00
commit 1581a94fc3
2 changed files with 57 additions and 12 deletions

View File

@ -189,16 +189,45 @@ describe('Util', function() {
describe('#template', function () { describe('#template', function () {
it('evaluates templates with a given data object', function () { it('evaluates templates with a given data object', function () {
var tpl = 'Hello {foo} and {bar}!'; var tpl = 'Hello {foo} and {baz }!';
var str = L.Util.template(tpl, { var str = L.Util.template(tpl, {
foo: 'Vlad', foo: 'Vlad',
bar: 'Dave' bar: 'Dave',
baz:function(o){
return o.bar;
}
}); });
expect(str).to.eql('Hello Vlad and Dave!'); expect(str).to.eql('Hello Vlad and Dave!');
}); });
it('check the cache', function () {
var tpl = 'Hello {foo} and {baz }!';
var str = L.Util.templateCache[tpl]({
foo: 'ladies',
baz: function(){
return 'gentlemen';
}
});
expect(str).to.eql('Hello ladies and gentlemen!');
});
it('evaluates templates with a function', function () {
var tpl = L.Util.compileTemplate('Hello { foo } and { bar}!',{});
var str1 = tpl({
foo: 'Vlad',
bar: 'Dave'
});
var str2 = tpl({
foo: '{Calvin}',
bar: '{Simon}'
});
expect(str1).to.eql('Hello Vlad and Dave!');
expect(str2).to.eql('Hello {Calvin} and {Simon}!');
});
it('does not modify text without a token variable', function () { it('does not modify text without a token variable', function () {
expect(L.Util.template('foo', {})).to.eql('foo'); expect(L.Util.template('foo', {})).to.eql('foo');
}); });

View File

@ -105,16 +105,32 @@ L.Util = {
return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&'); return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
}, },
template: function (str, data) { compileTemplate: function (str, data) {
return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) { /*jslint evil: true */
var value = data[key]; //from https://gist.github.com/padolsey/6008842
if (value === undefined) { return new Function(
throw new Error('No value provided for variable ' + str); 'o',
} else if (typeof value === 'function') { 'return "' + (
value = value(data); str.replace(/\"/g, '\\"').replace(/\{ *([\w_]+) *\}/g, function (_, $1) {
if (typeof data[$1] === 'function') {
return '" + o["' + $1 + '"](o) + "';
} else {
return '" + o["' + $1 + '"] + "';
}
})
) + '";'
);
},
templateCache: {},
template: function (str, data) {
if (str in this.templateCache) {
return this.templateCache[str](data);
} else {
this.templateCache[str] = this.compileTemplate(str, data);
return this.templateCache[str](data);
} }
return value;
});
}, },
isArray: function (obj) { isArray: function (obj) {