Django: Count forloop.first only if a second if condition is met

I have the following (oversimplified example):

{% for item in myitems  %}
  {% if item == "orange" %}
   {% if forloop.first %}
    {{item}}
  {% endif %}
 {% endif %}
{% endfor %}

Let's say that my list myitems is ['apple','orange','watermelon']. The first loop will be item=apple so it won't print the item because it is not "orange". In the second loop now we have item=orange but it no longer fulfills if forloop.first` so it won't print the item. I want a forloop.first that print only if it fulfills getting inside the if orange condition. How can I achieve this?

If I've correctly understood, you're basically looking for this piece of code:

{% for item in myitems  %}
    {% if item == "orange" and forloop.first %}
        {{item}}
    {% endif %}
{% endfor %}

A simple and should do the job. With the example you provided ['apple','orange','watermelon'], the rendered template would be blank.

I think you can print the element of myitems only once when condition is met using a variable in the template and changing its value when the condition is met:

{% set stop_loop="" %}

{% for item in myitems  %}
    {% if stop_loop %}
    {% elif item == "orange" %}
        {{item}}
        {% set stop_loop="true" %}
    {% endif %}
{% endfor %}

IMO, this kind of business logics should be in the view rather than template.

This is my solution based on previous comments

{% with False as stop_loop %}
{% for item in myitems  %}
    {% if stop_loop %}
    {% elif item == "orange" %}
        {{item}}
        {% update_variable True as stop_loop %}
    {% endif %}
{% endfor %}
{% endwith %}

And I need to register in templatetags the following:

@register.simple_tag
def update_variable(value):
    return value
Back to Top