In a Django template for loop, checking if current item different from previous item
Asked Answered
F

2

25

I'm new to django and can't find a way to get this to work in django templates. The idea is to check if previous items first letter is equal with current ones, like so:

{% for item in items %}
    {% ifequal item.name[0] previous_item.name[0] %}
        {{ item.name[0] }}
    {% endifequal %}
    {{ item.name }}<br />
{% endforeach %}

Maybe i'm trying to do this in wrong way and somebody can point me in right direction.

Feeze answered 21/10, 2010 at 9:49 Comment(1)
I'll post an off-topic mini answer - if you're looking to do something "nested", then ditch the .objects stuff and use .tree - you'll have to install django-mptt for that. I've gone through this a couple of days ago when writing hierarchical pages and categories, so just wondering ;) Cheers.Leshalesher
G
63

Use the {% ifchanged %} tag.

{% for item in items %}
    {% ifchanged item.name.0 %}
        {{ item.name.0 }}
    {% endifchanged %}
{% endfor %}

Also remember you have to always use dot syntax - brackets are not valid template syntax.

Git answered 21/10, 2010 at 10:8 Comment(3)
Man, you are the bestExcurvate
10 years later, still the exact answer to my problem. ThanksRubirubia
Also pay attention to thisSmatter
S
0

Thanks for the answer Daniel Roseman

Note that it only has access to the previous item if there is no other condition

Maybe I could not explain well, let me give an example

View.py:

...
context = {
    'cars': [
      {
        'brand': 'Ford',
        'model': 'Mustang',
        'year': '1964',
      },
      {
        'brand': 'Ford',
        'model': 'Bronco',
        'year': '1970',
      },
      {
        'brand': 'Ford',
        'model': 'Sierra',
        'year': '1981',
      },
      {
        'brand': 'Volvo',
        'model': 'XC90',
        'year': '2016',
      },
      {
        'brand': 'Volvo',
        'model': 'P1800',
        'year': '1964',
      }]
}
...

Templates:

{% for x in cars %}
    {% if forloop.counter == 1 %}
        if first condition true
        <span>{{x.brand}}</span>
    {% else %}
        if first condition false
        {% ifchanged x.brand %}
            <span>{{x.brand}}</span>
        {% else %}
            <span>{{x.name}}</span>
        {% endifchanged %}
    {% endif %}
{% endfor %}

In this case, according to the first condition(The condition can be anything), the first item is never compared with {% ifchanged %}, so as a result, you see two "Ford", even though they are both from the same brand.

So {% ifchanged %} check if a value has changed from the last iteration of a loop, if there is no other conditions.

Smatter answered 16/8, 2023 at 3:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.