1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 import datetime
29 import traceback
30 import logging
31
32 from django.conf import settings
33 from django import template
34
35 register = template.Library()
36
37 logger = logging.getLogger(__name__)
43
46 """ Formats a datetime.datetime object as time Ago. E.g. '3 days 2 hours 10 minutes' """
47 try:
48 ago = datetime.datetime.now() - value
49 except TypeError:
50 return str(value)
51 def plurals(val):
52 return val != 1 and "s" or ""
53 hours, remainder = divmod(ago.seconds, 3600)
54 mins, secs = divmod(remainder, 60)
55 if ago.days >= 365:
56 years = ago.days / 365
57 return "%s year%s" % (years, plurals(years))
58 if ago.days > 28:
59 months = ago.days / 30
60 return "%s month%s" % (months, plurals(months))
61 if ago.days > 0:
62 return "%s day%s" % (ago.days, plurals(ago.days))
63 if hours > 0:
64 return "%s hour%s" % (hours, plurals(hours))
65 if mins > 1:
66 return "%s minutes" % (mins)
67 if mins == 1:
68 return "a minute"
69 return "less than a minute"
70
73 """
74 Truncates a string after a given number of chars
75 Argument: Number of chars to truncate after
76 """
77 try:
78 length = int(arg)
79 except ValueError:
80 return value
81 if not isinstance(value, basestring):
82 value = str(value)
83 if (len(value) > length):
84 return value[:length] + "..."
85 else:
86 return value
87
90 """
91 Truncates a string after a given number of chars
92 Argument: Number of chars to truncate befor
93 """
94 try:
95 length = int(arg)
96 except ValueError:
97 return value
98 if not isinstance(value, basestring):
99 value = str(value)
100 if (len(value) > length):
101 return "..."+value[len(value)-length:]
102 else:
103 return value
104
107 try:
108 length = int(arg)
109 except ValueError:
110 return value
111 front = length/2-3
112 end = length/2-3
113
114 if not isinstance(value, basestring):
115 value = str(value)
116 try:
117 l = len(value)
118 if l < length:
119 return value
120 elif l >= length:
121 return value[:front]+"..."+value[l-end:]
122 except Exception, x:
123 logger.error(traceback.format_exc())
124 return value
125
129 "Subtracts the arg from the value"
130 return int(value) - int(arg)
131
136 """
137 Filter - returns a list containing range made from given value
138 Usage (in template):
139
140 <ul>{% for i in 3|get_range %}
141 <li>{{ i }}. Do something</li>
142 {% endfor %}</ul>
143
144 Results with the HTML:
145 <ul>
146 <li>0. Do something</li>
147 <li>1. Do something</li>
148 <li>2. Do something</li>
149 </ul>
150
151 Instead of 3 one may use the variable set in the views
152 """
153 return range( value )
154