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:
JavaScript
x
6
1
{% for asample in allsamples %}
2
{% ifchanged asample.brand %}
3
<h2>{{ asample.brand }}</h2>
4
{% endifchanged %}
5
{% endfor %}
6
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?
Advertisement
Answer
If you are asking about jinja2
solution, you can workaround it with if/else
and set
:
JavaScript
1
7
1
{% for asample in allsamples %}
2
{% if asample.brand != last_brand %}
3
<h2>{{ asample.brand }}</h2>
4
{% set last_brand = asample.brand %}
5
{% endif %}
6
{% endfor %}
7