Allow double quotes in template strings fixes #2120

This commit is contained in:
Jan Pieter Waagmeester 2013-10-23 15:14:59 +02:00
parent b0df9627b0
commit a7f2d1975f
2 changed files with 12 additions and 2 deletions

View File

@ -194,25 +194,27 @@ describe('Util', function() {
var str = L.Util.template(tpl, { var str = L.Util.template(tpl, {
foo: 'Vlad', foo: 'Vlad',
bar: 'Dave', bar: 'Dave',
baz:function(o){ baz: function (o) {
return o.bar; return o.bar;
} }
}); });
expect(str).to.eql('Hello Vlad and Dave!'); expect(str).to.eql('Hello Vlad and Dave!');
}); });
it('check the cache', function () { it('check the cache', function () {
var tpl = 'Hello {foo} and {baz }!'; var tpl = 'Hello {foo} and {baz }!';
var str = L.Util._templateCache[tpl]({ var str = L.Util._templateCache[tpl]({
foo: 'ladies', foo: 'ladies',
baz: function() { baz: function () {
return 'gentlemen'; return 'gentlemen';
} }
}); });
expect(str).to.eql('Hello ladies and gentlemen!'); expect(str).to.eql('Hello ladies and gentlemen!');
}); });
it('evaluates templates with a function', function () { it('evaluates templates with a function', function () {
var tpl = L.Util.compileTemplate('Hello { foo } and { bar}!',{}); var tpl = L.Util.compileTemplate('Hello { foo } and { bar}!',{});
@ -228,10 +230,17 @@ describe('Util', function() {
expect(str1).to.eql('Hello Vlad and Dave!'); expect(str1).to.eql('Hello Vlad and Dave!');
expect(str2).to.eql('Hello {Calvin} and {Simon}!'); 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');
}); });
it('supports templates with double quotes', function () {
expect(L.Util.template('He said: "{foo}"!', {
foo: 'Hello'
})).to.eql('He said: "Hello"!');
});
it('throws when a template token is not given', function () { it('throws when a template token is not given', function () {
expect(function () { expect(function () {
L.Util.template(tpl, {foo: 'bar'}); L.Util.template(tpl, {foo: 'bar'});

View File

@ -107,6 +107,7 @@ L.Util = {
compileTemplate: function (str, data) { compileTemplate: function (str, data) {
// based on https://gist.github.com/padolsey/6008842 // based on https://gist.github.com/padolsey/6008842
str = str.replace(/"/g, '\\\"');
str = str.replace(/\{ *([\w_]+) *\}/g, function (str, key) { str = str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
return '" + o["' + key + '"]' + (typeof data[key] === 'function' ? '(o)' : '') + ' + "'; return '" + o["' + key + '"]' + (typeof data[key] === 'function' ? '(o)' : '') + ' + "';
}); });