-
Notifications
You must be signed in to change notification settings - Fork 4
/
comparison.py
87 lines (68 loc) · 2.64 KB
/
comparison.py
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"""
Tags for performing basic value comparisons in templates.
"""
from django import template
COMPARISON_DICT = {
'less': lambda x: x < 0,
'less_or_equal': lambda x: x <= 0,
'greater_or_equal': lambda x: x >= 0,
'greater': lambda x: x > 0,
}
class ComparisonNode(template.Node):
def __init__(self, var1, var2, comparison, nodelist_true, nodelist_false):
self.var1 = template.Variable(var1)
self.var2 = template.Variable(var2)
self.comparison = comparison
self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
def render(self, context):
try:
result = cmp(self.var1.resolve(context),
self.var2.resolve(context))
if COMPARISON_DICT[self.comparison](result):
return self.nodelist_true.render(context)
# If either variable fails to resolve, return nothing.
except template.VariableDoesNotExist:
return ''
# If the types don't permit comparison, return nothing.
except TypeError:
return ''
return self.nodelist_false.render(context)
def do_comparison(parser, token):
"""
Compares two values.
Syntax::
{% if_[comparison] [var1] [var2] %}
...
{% else %}
...
{% endif_[comparison] %}
The {% else %} block is optional, and ``var1`` and ``var2`` may be
variables or literal values.
Supported comparisons are ``less``, ``less_or_equal``, ``greater``
and ``greater_or_equal``.
Examples::
{% if_less some_object.id 3 %}
<p>{{ some_object }} has an id less than 3.</p>
{% endif_less %}
{% if_greater_or_equal forloop.counter 4 %}
<p>This is at least the fifth time through the loop.</p>
{% else %}
<p>This is one of the first four trips through the loop.</p>
{% endif_greater_or_equal %}
"""
bits = token.contents.split()
if len(bits) != 3:
raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
end_tag = 'end' + bits[0]
nodelist_true = parser.parse(('else', end_tag))
token = parser.next_token()
if token.contents == 'else':
nodelist_false = parser.parse((end_tag,))
parser.delete_first_token()
else:
nodelist_false = template.NodeList()
comparison = bits[0].split('if_')[1]
return ComparisonNode(bits[1], bits[2], comparison, nodelist_true, nodelist_false)
register = template.Library()
for tag_name in ('if_less', 'if_less_or_equal', 'if_greater_or_equal', 'if_greater'):
register.tag(tag_name, do_comparison)