0

I'm trying to create an iteration like the a $i==0; $i++; from PHP in Django, based on a condition.

{% for item in event.products %}         
{% if item.category = "Treat" %}

Now - I want to be able to tell how many times has this condition been met (category = treat) and how to stop the for loop after 2 items that match that loop.

Thanks!

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274

2 Answers2

0

django template system does not permit breaks in for loops nor setting counters, even if elsewhere it is shown how to overcome this limitation in some cases or how to create new template tags that could help you, maybe you can calculate beforehand your requirements and prepare the list to be printed by slicing it in your view.

DRC
  • 4,898
  • 2
  • 21
  • 35
0

I agree with @DRC that this business logic is best done in your view code and not in the template.

If you still need a template solution:

{% regroup event.products by item.category as grouped_products %}

{% for group in grouped_products %}
    {% if group.grouper == "Treat" %}
        {% for item in group.list|slice:":2" %}
            {{ item.imageURL }}
        {% endfor %}
    {% endif %}
{% endfor %}

Documentation for slice and regroup.

Risadinha
  • 16,058
  • 2
  • 88
  • 91
  • Thanks for the help so far. That's great, but how would I then go about echoing some of the variables that I was echoing like so in the old code: {{ item.imageURL }} Unfortunately this will go in an ESP so there's no changint he view code. – Andrei Marin May 07 '18 at 15:34
  • `slice` still returns a list. You should be able to just iterate over it. I've changed the example. – Risadinha May 08 '18 at 05:46