Deal with property fallback in templating

eg. {prop1|prop2|"default"}

cf #820
This commit is contained in:
Yohan Boniface 2020-11-08 14:32:09 +01:00
parent b29adaa53f
commit ec275d64fe
2 changed files with 26 additions and 10 deletions

View file

@ -125,17 +125,25 @@ L.Util.usableOption = function (options, option) {
}; };
L.Util.greedyTemplate = function (str, data, ignore) { L.Util.greedyTemplate = function (str, data, ignore) {
// Don't throw error if some key is missing function getValue(data, path) {
return str.replace(/\{ *([\w_\:\.]+)(\|([^\}]+))? *\}/g, function (str, key, _, fallback) { var value = data
var path = key.split('.'),
leaf = path.length - 1, value = data;
for (var i = 0; i < path.length; i++) { for (var i = 0; i < path.length; i++) {
value = value[path[i]] value = value[path[i]]
if (value === undefined) { if (value === undefined) break;
if (ignore) value = str; }
else value = fallback || ''; return value;
break; }
}
return str.replace(/\{ *([\w_\:\."\|]+) *\}/g, function (str, key) {
var vars = key.split('|'), value, path;
for (var i = 0; i < vars.length; i++) {
path = vars[i];
if (path.startsWith('"') && path.endsWith('"')) value = path.substring(1, path.length -1); // static default value.
else value = getValue(data, path.split('.'));
}
if (value === undefined) {
if (ignore) value = str;
else value = '';
} }
return value; return value;
}); });

View file

@ -167,7 +167,15 @@ describe('L.Util', function () {
}); });
it('should handle fallback value if any', function () { 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.'); assert.equal(L.Util.greedyTemplate('A phrase with a {fr.var.bar|"default"}.', {}), 'A phrase with a default.');
});
it('should handle fallback var if any', function () {
assert.equal(L.Util.greedyTemplate('A phrase with a {fr.var.bar|fallback}.', {fallback: "default"}), 'A phrase with a default.');
});
it('should handle multiple fallbacks', function () {
assert.equal(L.Util.greedyTemplate('A phrase with a {fr.var.bar|try.again|"default"}.', {}), 'A phrase with a default.');
}); });
}); });