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:
{% 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.

Comments

  1. you can use {% if some_var == '3' %}

    ReplyDelete
  2. It works, but only for equal comparison :)

    ReplyDelete
  3. Yes, but if I want to compare between numbers such as 'a > b', any way to do this?

    ReplyDelete
  4. {% if a|add:0 > b|add:0 %}
    ...

    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.

    ReplyDelete
  5. Oh, yes, it's so kind of you, thank you for your help~

    ReplyDelete

Post a Comment

Popular posts from this blog

Improve font rendering for IntelliJ IDEA / Pycharm in Ubuntu

Fix - Updated from OSX El Capitan Gold Master to Final Release, andbeta update keeps showing in AppStore