Compare integer variable in django templates
Ever needed to compare some variable (that may come from db, forms, etc) in django templates with an integer?
Example:
The above example will not work. Django's template engine interprets the variable as a string.
Workaround for integer comparison:
By using the "add" filter, the variable is transformed into an integer.
Example:
{% if some_var == 3 %}
working
{% endif %}
The above example will not work. Django's template engine interprets the variable as a string.
Workaround for integer comparison:
{% if some_var|add:0 == 3 %}
working
{% endif %}
By using the "add" filter, the variable is transformed into an integer.
sounds hacky.
ReplyDeleteyou can use {% if some_var == '3' %}
ReplyDeleteIt works, but only for equal comparison :)
ReplyDeleteYes, but if I want to compare between numbers such as 'a > b', any way to do this?
ReplyDelete{% if a|add:0 > b|add:0 %}
ReplyDelete...
But don't write too much logic in templates.
Data should already come prepared for the template.
That's why django does not allow complex comparisons, with "and" and "or" combined.
Oh, yes, it's so kind of you, thank you for your help~
ReplyDeleteThanks for sharing. Django is the powerful framework of Python. Kanhasoft is the leading Django web development company in India and USA. With the team of 45 experienced Web developers, we are outsourcing mobile and web application services to Canada, USA, Denmark, Australia, South Africa and more.
ReplyDelete