Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 639
ronalds Avatar asked Oct 21 '10 09:10

ronalds


People also ask

What is Forloop counter in Django?

Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.

What does {% include %} do in Django?

From the documentation: {% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.

Can I use while loop in Django?

The key point is that you can't do this kind of thing in the Django template language.

What does {% include %} do?

{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.


1 Answers

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.

like image 172
Daniel Roseman Avatar answered Oct 22 '22 00:10

Daniel Roseman