Add templatefilter joinandor
authorMagnus Hagander <magnus@hagander.net>
Thu, 10 Sep 2020 12:52:41 +0000 (14:52 +0200)
committerMagnus Hagander <magnus@hagander.net>
Thu, 10 Sep 2020 12:52:41 +0000 (14:52 +0200)
This filter takes a list of a,b,c,d and turns it into "a, b, c and d"
or "a, b, c or d" depending on parameter given.

pgweb/core/templatetags/pgfilters.py

index 4fa2d89d3b6f573524e0d4a218a8224d1aa66b71..c3c8e4ced13885750ed959e9e71be0d46f3b0249 100644 (file)
@@ -83,6 +83,19 @@ def release_notes_pg_minor_version(minor_version, major_version):
     return minor_version
 
 
+@register.filter()
+def joinandor(value, andor):
+    # Value is a list of objects. Join them on comma, add "and" or "or" before the last.
+    if len(value) == 1:
+        return str(value[0])
+
+    if not isinstance(value, list):
+        # Must have a list to index from the end
+        value = list(value)
+
+    return ", ".join([str(x) for x in value[:-1]]) + ' ' + andor + ' ' + str(value[-1])
+
+
 @register.simple_tag(takes_context=True)
 def git_changes_link(context):
     return mark_safe('<a href="https://git.postgresql.org/gitweb/?p=pgweb.git;a=history;f=templates/{}">View</a> change history.'.format(context.template_name))