summaryrefslogtreecommitdiffstats
path: root/utils/filters.py
diff options
context:
space:
mode:
Diffstat (limited to 'utils/filters.py')
-rw-r--r--utils/filters.py39
1 files changed, 39 insertions, 0 deletions
diff --git a/utils/filters.py b/utils/filters.py
new file mode 100644
index 0000000..eb0e1c8
--- /dev/null
+++ b/utils/filters.py
@@ -0,0 +1,39 @@
+from app import app
+from jinja2 import contextfilter
+from jinja2.filters import make_attrgetter
+
+
+@app.template_filter('selectattr')
+@contextfilter
+def do_selectattr(*args, **kwargs):
+ return _select_or_reject(args, kwargs, lambda x: x)
+
+
+@app.template_filter('rejectattr')
+@contextfilter
+def do_rejectattr(*args, **kwargs):
+ return _select_or_reject(args, kwargs, lambda x: not x)
+
+
+def _select_or_reject(args, kwargs, modfunc):
+ context = args[0]
+ seq = args[1]
+
+ try:
+ attr = args[2]
+ except LookupError:
+ raise FilterArgumentError('Missing parameter for attribute name')
+ transfunc = make_attrgetter(context.environment, attr)
+
+ try:
+ name = args[3]
+ args = args[4:]
+ func = lambda item: context.environment.call_test(
+ name, item, args, kwargs)
+ except LookupError:
+ func = bool
+
+ if seq:
+ for item in seq:
+ if modfunc(func(transfunc(item))):
+ yield item