Reputation: 11774
I have a conditional within a Django template that will create text a certain color if the expression evaluates true and another color if not. Note that I'm not actually going to have my styles in the HTML like in this example, but this makes it easier to give an example. Here's the code:
<div class="span6 resultsBox">
<h2>Items:
{% if user.items >= user.itemsQuota %}
<span id="items" style="color:green">{{ user.items}} </span>
{% else %}
<span id="items" style="color:white">{{ user.items }} </span>
{% endif %}
/ {{user.itemsQuota }}.
</h2><br />
</div>
No matter what I do, the resulting span
text is green! Normally I'd think there's something wrong with my models and how they are calculating equality, but even when the out put is something like 100/1000
, where clearly {{ user.items }}
is less than {{ user.itemsQuota }}
, the green font occurs! What am I missing here with my conditionals?
Upvotes: 0
Views: 64
Reputation: 203304
My guess would be user.items
is a string and user.itemsQuota
is a number. In Python (before 3.x), '100' > 1000
is True.
Quick demo:
from django.template import Template, Context
from django.conf import settings
settings.configure()
t = Template('{% if a > b %} a > b {% else %} a <= b {% endif %}')
print t.render(Context({ 'a' : '100', 'b' : 1000 }))
print t.render(Context({ 'a' : 100 , 'b' : 1000 }))
prints:
a > b
a <= b
If you want a template-only solution, this works:
t = Template('{% if a|add:"0" > b|add:"0" %} a > b {% else %} a <= b {% endif %}')
(because add
coerces the values to integers)
Upvotes: 3