From d4b60e9304734a4e74b237c0323df594d25010de Mon Sep 17 00:00:00 2001 From: Jessica McKellar Date: Fri, 25 Oct 2013 12:54:03 -0400 Subject: [PATCH] Add a custom template filter for formatting displaying lists of items in emails. We do this operation several times in the digest e-mails. (imported from commit 7b906bad582c628d4461637dc7af374df349e09a) --- zerver/lib/digest.py | 6 ----- zerver/templatetags/app_filters.py | 38 ++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 6 deletions(-) create mode 100644 zerver/templatetags/app_filters.py diff --git a/zerver/lib/digest.py b/zerver/lib/digest.py index b8a71dec8d..275b387fbc 100644 --- a/zerver/lib/digest.py +++ b/zerver/lib/digest.py @@ -18,12 +18,6 @@ from zerver.models import UserProfile, UserMessage, Recipient, Stream, \ # 4. Interesting stream traffic, as determined by the longest and most # diversely comment upon topics. -def and_n_others(things, limit): - # A helper for the commonly appended "and N other(s)" string, with - # the appropriate pluralization. - return " and %d other%s" % (len(things) - limit, - "" if len(things) == limit + 1 else "s") - def gather_hot_conversations(user_profile, stream_messages): # Gather stream conversations of 2 types: # 1. long conversations diff --git a/zerver/templatetags/app_filters.py b/zerver/templatetags/app_filters.py new file mode 100644 index 0000000000..d54eff093f --- /dev/null +++ b/zerver/templatetags/app_filters.py @@ -0,0 +1,38 @@ +from django.template import Library + +register = Library() + +def and_n_others(values, limit): + # A helper for the commonly appended "and N other(s)" string, with + # the appropriate pluralization. + return " and %d other%s" % (len(values) - limit, + "" if len(values) == limit + 1 else "s") + +@register.filter(name='display_list', is_safe=True) +def display_list(values, display_limit): + """ + Given a list of values, return a string nicely formatting those values, + summarizing when you have more than `display_limit`. Eg, for a + `display_limit` of 3 we get the following possible cases: + + Jessica + Jessica and Waseem + Jessica, Waseem, and Tim + Jessica, Waseem, Tim, and 1 other + Jessica, Waseem, Tim, and 2 others + """ + if len(values) == 1: + # One value, show it. + display_string = "%s" % (values[0],) + elif len(values) <= display_limit: + # Fewer than `display_limit` values, show all of them. + display_string = ", ".join( + "%s" % (value,) for value in values[:-1]) + display_string += " and %s" % (values[-1],) + else: + # More than `display_limit` values, only mention a few. + display_string = ", ".join( + "%s" % (value,) for value in values[:display_limit]) + display_string += and_n_others(values, display_limit) + + return display_string