Mercurial > libervia-backend
diff src/tools/common/template.py @ 2402:f905dfe69fcc
template: new item_value filter
this filter is used with XMLUI to specify filters before using a generate method.
author | Goffi <goffi@goffi.org> |
---|---|
date | Fri, 27 Oct 2017 18:17:35 +0200 |
parents | 221478058d8a |
children | dec31114c402 |
line wrap: on
line diff
--- a/src/tools/common/template.py Fri Oct 27 18:13:25 2017 +0200 +++ b/src/tools/common/template.py Fri Oct 27 18:17:35 2017 +0200 @@ -203,6 +203,7 @@ self.env.filters['date_days'] = self._date_days self.env.filters['xmlui_class'] = self._xmlui_class self.env.filters['attr_escape'] = self.attr_escape + self.env.filters['item_filter'] = self._item_filter self.env.filters['adv_format'] = self._adv_format def installTranslations(self): @@ -365,6 +366,34 @@ continue return u' '.join(classes) or None + def _item_filter(self, item, filters): + """return item's value, filtered if suitable + + @param item(object): item to filter + value must have name and value attributes, + mostly used for XMLUI items + @param filters(dict[unicode, (callable, dict, None)]): map of name => filter + if filter is None, return the value unchanged + if filter is a callable, apply it + if filter is a dict, it can have following keys: + - filters: iterable of filters to apply + - filters_args: kwargs of filters in the same order as filters (use empty dict if needed) + - template: template to format where {value} is the filtered value + """ + value = item.value + filter_ = filters.get(item.name, None) + if filter_ is None: + return value + elif isinstance(filter_, dict): + filter_args = filter_.get(u'filter_args') + for idx, f_name in enumerate(filter_.get(u'filters', [])): + kwargs = filter_args[idx] if filter_args is not None else {} + value = self.env.filters[f_name](value, **kwargs) + template = filter_.get(u'template', u'{value}') + return template.format(value=value) + else: + return filter_(item.value) + def _adv_format(self, value, template, **kwargs): """Advancer formatter