Naive support for nested variables in templates

cf #600
This commit is contained in:
Yohan Boniface 2018-08-01 09:43:55 +02:00
parent 1cbf140f57
commit 9539aa0efc
2 changed files with 22 additions and 5 deletions

View file

@ -125,11 +125,16 @@ L.Util.usableOption = function (options, option) {
L.Util.greedyTemplate = function (str, data, ignore) {
// Don't throw error if some key is missing
return str.replace(/\{ *([\w_\:]+) *\}/g, function (str, key) {
var value = data[key];
return str.replace(/\{ *([\w_\:\.]+) *\}/g, function (str, key) {
var path = key.split('.'),
leaf = path.length - 1, value = data;
for (var i = 0; i < path.length; i++) {
value = value[path[i]]
if (value === undefined) {
if (ignore) value = str;
else value = '';
break;
}
}
return value;
});

View file

@ -146,6 +146,18 @@ describe('L.Util', function () {
assert.equal(L.Util.greedyTemplate('A phrase with a {variable:fr}.', {}, true), 'A phrase with a {variable:fr}.');
});
it('should replace nested variables', function () {
assert.equal(L.Util.greedyTemplate('A phrase with a {fr.var}.', {fr: {var: 'value'}}), 'A phrase with a value.');
});
it('should not fail if nested variable is missing', function () {
assert.equal(L.Util.greedyTemplate('A phrase with a {fr.var.foo}.', {fr: {var: 'value'}}), 'A phrase with a .');
});
it('should not fail with nested variables and no data', function () {
assert.equal(L.Util.greedyTemplate('A phrase with a {fr.var.foo}.', {}), 'A phrase with a .');
});
});
describe('#TextColorFromBackgroundColor', function () {