Minimal fallback handling in templating

eg. {var|defaultvalue}

cf #820
This commit is contained in:
Yohan Boniface 2020-11-08 12:07:07 +01:00
parent 450271b1e2
commit b29adaa53f
2 changed files with 6 additions and 2 deletions

View file

@ -126,14 +126,14 @@ 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) {
return str.replace(/\{ *([\w_\:\.]+)(\|([^\}]+))? *\}/g, function (str, key, _, fallback) {
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 = '';
else value = fallback || '';
break;
}
}

View file

@ -166,6 +166,10 @@ describe('L.Util', function () {
assert.equal(L.Util.greedyTemplate('A phrase with a {fr.var.foo}.', {}), 'A phrase with a .');
});
it('should handle fallback value if any', function () {
assert.equal(L.Util.greedyTemplate('A phrase with a {fr.var.foo|default}.', {}), 'A phrase with a default.');
});
});
describe('#TextColorFromBackgroundColor', function () {