From ec275d64fe9f835597c95cfacb329093a3fbd5e7 Mon Sep 17 00:00:00 2001 From: Yohan Boniface Date: Sun, 8 Nov 2020 14:32:09 +0100 Subject: [PATCH] Deal with property fallback in templating eg. {prop1|prop2|"default"} cf #820 --- umap/static/umap/js/umap.core.js | 26 +++++++++++++++++--------- umap/static/umap/test/Util.js | 10 +++++++++- 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/umap/static/umap/js/umap.core.js b/umap/static/umap/js/umap.core.js index 0bbdb6ea..07bab3cc 100644 --- a/umap/static/umap/js/umap.core.js +++ b/umap/static/umap/js/umap.core.js @@ -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) { - if (ignore) value = str; - else value = fallback || ''; - break; - } + 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 = ''; } return value; }); diff --git a/umap/static/umap/test/Util.js b/umap/static/umap/test/Util.js index fd6b5ebf..d990028e 100644 --- a/umap/static/umap/test/Util.js +++ b/umap/static/umap/test/Util.js @@ -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.'); }); });