changeset 2425:d294527bd46f

template: added dict_ext filter to extend a dictionary
author Goffi <goffi@goffi.org>
date Thu, 09 Nov 2017 07:54:28 +0100
parents 467ddb437a71
children 6c39f30444a0
files src/tools/common/template.py
diffstat 1 files changed, 19 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/src/tools/common/template.py	Wed Nov 08 08:31:21 2017 +0100
+++ b/src/tools/common/template.py	Thu Nov 09 07:54:28 2017 +0100
@@ -207,6 +207,7 @@
         self.env.filters['attr_escape'] = self.attr_escape
         self.env.filters['item_filter'] = self._item_filter
         self.env.filters['adv_format'] = self._adv_format
+        self.env.filters['dict_ext'] = self._dict_ext
         # custom tests
         self.env.tests['in_the_past'] = self._in_the_past
 
@@ -485,6 +486,24 @@
         # jinja use string when no special char is used, so we have to convert to unicode
         return unicode(template).format(value=value, **kwargs)
 
+    def _dict_ext(self, source_dict, extra_dict, key=None):
+        """extend source_dict with extra dict and return the result
+
+        @param source_dict(dict): dictionary to extend
+        @param extra_dict(dict, None): dictionary to use to extend first one
+            None to return source_dict unmodified
+        @param key(unicode, None): if specified extra_dict[key] will be used
+            if it doesn't exists, a copy of unmodified source_dict is returned
+        @return (dict): resulting dictionary
+        """
+        if extra_dict is None:
+            return source_dict
+        if key is not None:
+            extra_dict = extra_dict.get(key, {})
+        ret = source_dict.copy()
+        ret.update(extra_dict)
+        return ret
+
     ## custom tests ##
 
     def _in_the_past(self, timestamp):