ifchanged Tag

Logic

Documentation

Used within a loop to output something if one or more values has changed since the last loop iteration.

Variable

foods = [
    {'name': 'Apple', 'category': 'Fruit'},
    {'name': 'Banana', 'category': 'Fruit'},
    {'name': 'Grape', 'category': 'Fruit'},
    {'name': 'Hamburger', 'category': 'Meat'},
    {'name': 'Pepper', 'category': 'Vegetable'},
    {'name': 'Corn', 'category': 'Vegetable'}
]

Template
{% for food in foods %}
  {% ifchanged food.category %}<h3>{{ food.category }}</h3>{% endifchanged %}
  <p>{{ food.name }}</p>
{% endfor %}

Result

<h3>Fruit</h3>
<p>Apple</p>
<p>Banana</p>
<p>Grape</p>

<h3>Meat</h3>
<p>Hamburger</p>

<h3>Vegetable</h3>
<p>Pepper</p>
<p>Corn</p>

Notice that the h3 elements only get inserted if the category has changed since the previous iteration.


Did we get something wrong? Is there a use case for the ifchanged tag that we should add? Please let us know.

Send Feedback

Official Documentation
This page last updated on April 14, 2020, 6:19 p.m. EST