diff options
Diffstat (limited to 'foundry/template_filters.py')
-rw-r--r-- | foundry/template_filters.py | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/foundry/template_filters.py b/foundry/template_filters.py new file mode 100644 index 0000000..6dec2e7 --- /dev/null +++ b/foundry/template_filters.py | |||
@@ -0,0 +1,53 @@ | |||
1 | # vim: set filencoding=utf8 | ||
2 | """ | ||
3 | Foundry Template Filters | ||
4 | |||
5 | @author: Mike Crute (mcrute@gmail.com) | ||
6 | @organization: SoftGroup Interactive, Inc. | ||
7 | @date: May 03, 2010 | ||
8 | """ | ||
9 | |||
10 | |||
11 | from datetime import datetime | ||
12 | from foundry.utils import frozendict | ||
13 | |||
14 | |||
15 | def pluralize(word, how_many=1): | ||
16 | "Naive pluralization function." | ||
17 | return word if how_many == 1 else word + "s" | ||
18 | |||
19 | |||
20 | def nice_date_delta(from_date, to_date=datetime.now()): | ||
21 | """ | ||
22 | Provides a friendly text representation (ie. 7 months) | ||
23 | for the delta between two dates. | ||
24 | """ | ||
25 | delta = to_date - from_date | ||
26 | |||
27 | months = delta.days / 30 | ||
28 | if months > 0: | ||
29 | return "{0} {1}".format(months, pluralize("month", months)) | ||
30 | |||
31 | weeks = delta.days / 7 | ||
32 | if weeks > 0: | ||
33 | return "{0} {1}".format(weeks, pluralize("week", weeks)) | ||
34 | |||
35 | if delta.days > 0: | ||
36 | return "{0} {1}".format(delta.days, pluralize("day", delta.days)) | ||
37 | |||
38 | hours = delta.seconds / (60 * 60) | ||
39 | if hours > 0: | ||
40 | return "{0} {1}".format(hours, pluralize("hour", hours)) | ||
41 | |||
42 | minutes = delta.seconds / 60 | ||
43 | if minutes > 0: | ||
44 | return "{0} {1}".format(minutes, pluralize("minute", minutes)) | ||
45 | |||
46 | return "seconds ago" | ||
47 | |||
48 | |||
49 | #: Template filter registry | ||
50 | TEMPLATE_FILTERS = frozendict({ | ||
51 | 'nice_date_delta': nice_date_delta, | ||
52 | 'pluralize': pluralize, | ||
53 | }) | ||