Deal with property fallback in templating
eg. {prop1|prop2|"default"} cf #820
This commit is contained in:
parent
b29adaa53f
commit
ec275d64fe
2 changed files with 26 additions and 10 deletions
|
@ -125,17 +125,25 @@ 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, _, fallback) {
|
||||
var path = key.split('.'),
|
||||
leaf = path.length - 1, value = data;
|
||||
function getValue(data, path) {
|
||||
var value = data
|
||||
for (var i = 0; i < path.length; i++) {
|
||||
value = value[path[i]]
|
||||
if (value === undefined) break;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
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 = fallback || '';
|
||||
break;
|
||||
}
|
||||
else value = '';
|
||||
}
|
||||
return value;
|
||||
});
|
||||
|
|
|
@ -167,7 +167,15 @@ describe('L.Util', 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.');
|
||||
});
|
||||
|
||||
});
|
||||
|
|
Loading…
Reference in a new issue