Search code examples
pythondjango-templatesjinja2

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


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?


Solution

  • 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 %}