Not able to use conditional tags in for loop in Django template file

Question:

I’m using Django 1.4/python 2.7.9 (because I’m required to, I know 1.4 is pretty old now) and I’m pretty green with django/python. In my template file, I seem to be unable to use any of the cool conditional tags like ifchanged or ifequal within a for loop.

For example:

{% for asample in allsamples %}
    {% ifchanged asample.brand %}
        <h2>{{ asample.brand }}</h2>
    {% endifchanged %}
{% endfor %}

This throws the error “Encountered unknown tag ‘ifchanged’. Jinja was looking for the following tags: ‘endfor’ or ‘else’. The innermost block that needs to be closed is ‘for’.”

I’ve tried ifequals in there too – same error. Is there something preventing me from using other tags within the for loop?

Asked By: Todd

||

Answers:

If you are asking about jinja2 solution, you can workaround it with if/else and set:

{% for asample in allsamples %}
    {% if asample.brand != last_brand %}
        <h2>{{ asample.brand }}</h2>
        {% set last_brand = asample.brand %}
    {% endif %}
{% endfor %}
Answered By: alecxe

I was using Jinja 3.1.2, and I found this solution:

{% for asample in allsamples %}
    {% if loop.changed(asample.brand) %}
        <h2>{{ asample.brand }}</h2>
    {% endif %}
{% endfor %}
Answered By: Bobort
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.