0

My context is an integer array, I'm trying to make a table where every number is compared to the previous one and I will display an arrow indicating if this number has increased or decreased.

This is what I'm trying to make

{% for number in object_list %}
{% if forloop.first %}
{% set prev_number = number %}
{%endif%}{%endfor%}

{% for number in object_list %}
{% if number > prev_number %}
...
{% else %}
...
{% endif %}
{% set prev_number = number %}
{% endfor %}

I know there is not {%set%} tag in django is there any tag equivalent to it? something like {%with%} but doesn't require {% endwith %}

or a template tag that does it or I should do it in the views.

  • {% ifchanged %} exists, but it doesn't let you compare to check for greater/less than. This may work for you: https://stackoverflow.com/a/32801096/9461432 – Tim Nyborg Apr 08 '21 at 09:49
  • @Hazem gamal: As you mentioned, you should do it in the view. You can add a dynamic attribute to each list element like `obj.change = obj.value - previous_value`. Then all you have to do in the template is display an appropriate arrow based on `obj.change`. The reason there is no `set` tag in Django is to discourage using extra logic in the template. – evergreen Apr 08 '21 at 11:37
  • @evergreen I'm trying to add it through views, I made a comparing function in views that make a list of 0, 1 and 2. 0 means equal, 1 means greater than, 2 means less. and trying to send it with context. But I have another issue with sending it with my context as my original view class is a ListView. I made another [quesiton](https://stackoverflow.com/questions/67011272/django-listview-how-to-zip-context-data-with-another-context) with current issue – Hazem gamal Apr 08 '21 at 20:20
  • as @TimNyborg said `ifchanged` exists, but not for graeter/less than, but if ever use it, pay attention to [this](https://stackoverflow.com/a/76910408/14821727) – amirmohammad Aug 16 '23 at 15:43

0 Answers0