From b29adaa53f2cf764898fe53bceea66756a067e29 Mon Sep 17 00:00:00 2001 From: Yohan Boniface Date: Sun, 8 Nov 2020 12:07:07 +0100 Subject: [PATCH] Minimal fallback handling in templating eg. {var|defaultvalue} cf #820 --- umap/static/umap/js/umap.core.js | 4 ++-- umap/static/umap/test/Util.js | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/umap/static/umap/js/umap.core.js b/umap/static/umap/js/umap.core.js index 1f3f8cbf..0bbdb6ea 100644 --- a/umap/static/umap/js/umap.core.js +++ b/umap/static/umap/js/umap.core.js @@ -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; } } diff --git a/umap/static/umap/test/Util.js b/umap/static/umap/test/Util.js index 03004efc..fd6b5ebf 100644 --- a/umap/static/umap/test/Util.js +++ b/umap/static/umap/test/Util.js @@ -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 () {